user2094178
user2094178

Reputation: 9444

Rails render partial with multiple objects

This code is working fine:

<%= render 'sidebars/pages', :object => @categories = pages , :object => { @myobject => '1', @mmyobject => '2' } %>

If I change to this:

<%= render 'sidebars/pages', :object => { @categories => pages, @myobject => '1', @mmyobject => '2' } %>

Then I receive a error from the partial when it try to iterate @categories:

undefined method `each' for nil:NilClass

I'm very new to ruby and rails also, I appreciate any help.

Cheers!

Upvotes: 8

Views: 12314

Answers (2)

Stuart M
Stuart M

Reputation: 11588

When you pass an :object to a Rails partial, a local variable (not an instance variable, beginning with @) is defined within the partial which has the same name as the partial. So for the partial sidebars/_pages.html.erb, your local variable will be called pages.

The value of the pages local variable is the Hash you passed as the value of the :object option, and none of the instance variables you had in your "outer" view will be available (such as @categories or @myobject). So you'll need to access those via the pages local variable.

You're probably looking for something like this:

<%= render 'sidebars/pages', :object => { :categories => @categories, :myobject => '1', :mmyobject => '2' } %>

And in sidebars/_pages.html.erb, you might have something like this:

<p><%= pages[:myobject] %></p>

<ul>
<% pages[:categories].each do |category| %>
  <li><%= category %></li>
<% end %>
</ul>

See the Rails Guide to Layouts and Rendering's Partials section for more details.

Update:

An even better solution would be to use the :locals option, which accepts a Hash whose keys become local variables with the partial. For instance:

<%= render 'sidebars/pages', :locals => { :categories => @categories, :myobject => '1', :mmyobject => '2' } %>

And in sidebars/_pages.html.erb, you might have something like this:

<p><%= myobject %></p>
<p><%= mmyobject %></p>

<ul>
<% categories.each do |category| %>
  <li><%= category %></li>
<% end %>
</ul>

Upvotes: 15

user2094178
user2094178

Reputation: 9444

This line of code as mentioned above:

<%= render 'sidebars/pages', :object => @categories = pages , :object => { @myobject => '1', @mmyobject => '2' } %

Actually does not raise any errors but also does not pass @myobject and @mmyobject to the view.

Below is the correct* approach for specifying multiple objects with the render method:

<%= render 'sidebars/pages', :object => [@categories = pages, @myobject = '2'] %>

Like this I can pass multiple objects to the view, without having to define :object more than once.

*at least for my knowledge scope

Upvotes: 1

Related Questions