Fellow Stranger
Fellow Stranger

Reputation: 34013

Pass a value to an instance variable in the controller

I have a show action in which I want to pass a value to the view, quantity: 8 , via the queried instance variable.

Here, the creation of the instance variable:

@organizer = Organizer.find(params[:id])

I guess I could pass this value by either creating a virtual attribute with attr_accessor or by passing a value to params.

Assuming I'm right about having these two choices, I have two questions.

Question 1: Does any of the two ways have clear advantages over the other?

Question 2: How would I go about adding this value to the params accessible to the view?

Upvotes: 0

Views: 443

Answers (2)

Aleks
Aleks

Reputation: 5330

Question 1: Does any of the two ways have clear advantages over the other?

Approach with params is not a real choice. As said, params are used to pass parameters from view to controller and not vise-versa. The clear advantage is that - that is how it is used by convention.

Question 2: How would I go about adding this value to the params accessible to the view?

You don't even try. If you mean by this - to set params and pass it to the view. Use instance variable like @quantity = 8 or you could set-up global variable or new table for variable values, and then set the @quantity with that value

Upvotes: 1

Billy Chan
Billy Chan

Reputation: 24815

As OP said it's good practice to minimize instance variables generated in controller, which is better to be only 1.

So, about how to use quantity, I will make decision as follows:

  1. If this has nothing to do with model, I will use a helper directly and call this helper in view.

  2. If this has something to do with model but no relation to controller, I will make such method in model.

  3. If this relates to both model and controller, and the pattern could be only once, I will use one more instance variable. It's not good, but only once, so forgive it.

  4. If this relates to both model and controller, but expected to appear more than once, I will use a Presenter or Decorator pattern.

And param would not be in my consideration.

Upvotes: 1

Related Questions