Ruby-on-rails: rendering partial elements for each element in a list

I have the following in a view (.html.erb):

<% @posts = GetAllPostsFunctions %> (removed for berivity) <% @posts.each do |post| %> <%= post.title %> <%= render :partial => "posts/post_show" %> <% end %> 

The posts_show partiality has the following:

 .... <td><%=h @post.title %> </td> 

But I get the following error

 You have a nil object when you didn't expect it! The error occurred while evaluating nil.title 

Any ideas?

+6
ruby-on-rails
source share
4 answers

Since the post variable in each loop is a locale variable, you must make it available for partial:

 <%= render :partial => "posts/post_show", :locals => {:post => post} %> 

Then you can access the header through a local variable entry:

 <td><%=h post.title %> </td> 

You can also simplify all this by providing messages as a collection. Take a look at the Rails documentation for more information:

http://api.rubyonrails.org/classes/ActionController/Base.html#M000658

+7
source share

You can also just stuff using: collection for render: partial. Which pass each element to a value for: collection for a local variable that shares the name of your partial.

 <% @posts = GetAllPostsFunctions %> (removed for berivity) <%= render :partial => "posts/post_show", :collection => @posts %> 

In this case, Rails will display post_show for each item in @posts with the local post_show variable set for the current item. It also provides convenient counter methods.

Successful use of this approach will require renaming the application / views / posts / _post_show.html.erb, partial to app / views / posts / _post.html.erb, or changing each instance of the post in your partial post_show. If you renamed partial to regular _post.html.erb, which then allows you to simply:

 <%= render :partial => @posts %> 

which will be partial for each individual post in the @posts variable.

+16
source share

It doesn't seem like you are setting @post to partial, so when it evaluates to partial, it gets a null link.

Alternatively, make sure your mail picker functions actually return something

0
source share

I'm not sure, but I think in partial you need to do post.title not @post.title

Sorry if I misunderstood you, I'm new to rails.

0
source share

All Articles