1

So it seems that more and more people are suggesting that it is a bad idea to actually use instance variables in controller. That you should just send the variable with render into the view.

But when I do it like this for instance:

def index
        users = User.all
        render 'index', users: users
end

Then I am unable to use the :users symbol in the index view and iterate over it for instance. It will throw an error: undefined methodeach' for :users:Symbol` for me.

Is it even a good idea to try to do so? I thought I would give it a try and see how it will work out. But right now I cannot even get it to work...

2
  • So the code works using instance variables but you're just trying to see if there's a way to do it without? Commented Oct 17, 2014 at 18:40
  • Pretty much, in my application I am getting to a point where I have like 4 partials rendered to one page, and this creates a state where one method in a controller can contain many many instance variables which seems to be not considered a good way of doing things in Rails community. So I am looking for ways to do better. Commented Oct 17, 2014 at 18:43

1 Answer 1

3

users will be a variable in your view, not a symbol.

To iterate over it, you will need to call users.each instead of :users.each.

Sign up to request clarification or add additional context in comments.

5 Comments

Tried that too but then it tells me that users is a undefined local variable.
Ahh, try wrapping users: users in a locals hash. So, your render line would be render 'index', locals: {users: users}
Should it not matter after Rails 4? I thought it was the same thing now.
But one more question, do you think this method is better than using instance variables then?
I think instance variables are fine, especially for the main template. Local variables are useful/should be used for rendering partials, but for a full, main template, an instance variable is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.