render partial :object vs :locals

Ruby on-Rails

Ruby on-Rails Problem Overview


<%= render :partial => 'partial/path', :locals => {:xyz => 'abc'} %>

vs

<%= render :partial => 'partial/path', :object => @some_object %>

I think the first one make a local variable named xyz available in the partial and the second one makes a local variable named object available in the partial. So what is the difference? (Besides locals allows more than one variable)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

The second form

render :partial => 'account', :object => @some_account

will make sure the account variable in the partial will be set to @some_account. You can rename the variable using the :as option.

The biggest advantage of the :locals is that

  • you have very clear control over the objects and names
  • you can assign more than 1 variable

So you could do something like

render partial => 'some_view', :locals => { :user => account.user, :details => some_details_we_retrieved }

making a clear seperation possible when needed.

The disadvantage of the :locals approach is that it is more verbose, and sometimes a simple

render :partial => 'account'

is identical to

render :partial => 'account', :locals => {:account => @account }

So use the one which suits you the best (or where it suits the best).

Solution 2 - Ruby on-Rails

In the second case using :object will define a variable with the same name as the partial by default. If my partial template is named _user.html.erb then there will be a local variable named "user" defined in the template.

You can specify a different variable name with :as => "another_name".

This is documented here: http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html , here: http://apidock.com/rails/ActionView/PartialRenderer

...and for older Rails (version <= v3.09): http://apidock.com/rails/ActionView/Partials

Solution 3 - Ruby on-Rails

If you're using Rails 3+, there's an even easier syntax to use:

# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render 'account', account: @buyer %>

Source: Action View Partials

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris MuenchView Question on Stackoverflow
Solution 1 - Ruby on-RailsnathanvdaView Answer on Stackoverflow
Solution 2 - Ruby on-RailsWizard of OgzView Answer on Stackoverflow
Solution 3 - Ruby on-RailsrxgxView Answer on Stackoverflow