user502052
user502052

Reputation: 15257

Passing from using '@user' to using 'user' in 'html.erb' files: how and why?

I am using Ruby on Rails 3 and I was advised (@user is a global variable, you can't 'localize' it. I would suggest passing local variables from your controller in the same way.) to use variables like user instead of @user in view files. Why to do that, exactly?.

So, I am considering pass from using @user to using user. That is, (in html.erb file) from using

@user.name

to using

user.name

At this time, for example, in the show method of my controller I have:

def show
  @user = Users.find(1)
  ...
end

What I have to change in the controller to do that works in views?

Upvotes: 0

Views: 207

Answers (3)

mikewilliamson
mikewilliamson

Reputation: 24793

This is only something you need to worry about when the same partial is called in the views from more than one controller.

Having a partial that is using @user in it (likely set in a users_controller), means that the moment you call that partial in a view from some other controller (for example; accounts_controller) that does not set @users you will get an error. If you reference only local variables in your partial you can set them as needed from any controller with the :locals hash that was described.

Upvotes: 1

farnoy
farnoy

Reputation: 7776

Take a look at this Rails Best Practice. Using local variables is preferable way when rendering partials (those view files which start with a _). That's because you'll need review your controller's code to know about instance variable.

Upvotes: 0

apneadiving
apneadiving

Reputation: 115531

That's non sense, only instance_variables are sent from the controller to the view.

Nikita Rybak was not wrong in his answer, he just passed the instance variable contained in his view (@current_user) to a partial where it has a different name (user):

 :locals => { :user => @current_user }

he concluded very well:

Local variables are local, so you don't need @ to refer them.

Indeed you have two choices when working with a partial:

  • assume it has access to the instance variable (which is not advised)

  • pass the instance variable to the partial with a local name which is the Rails' way

Upvotes: 1

Related Questions