开发者

ruby-on-rails: rendering partials on each item 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 partial 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?


You can also simply things by using the :collection for render :partial. Which pass each item in the value for :collection to a local variable sharing the name of your partial.

<% @posts = GetAllPostsFunctions %>   (removed for berivity)

<%= render :partial => "posts/post_show", :collection => @posts %>

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

Successfully using this approach would require renaming the app/views/posts/_post_show.html.erb partial to app/views/posts/_post.html.erb to or changing every occurance of post in your partial to post_show. If you renamed the partial to the conventional _post.html.erb which will then allow you to simply do:

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

Which will render the partial for every single post in the @posts variable.


Since the post variable in the each loop is a locale variable you have to make it available to the partial:

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

You can then access the title through the local variable post:

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

You could also simplify the whole thing by rendering the posts as collection. Take a look at the Rails documentation for more information:

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


It doesn't look like you're setting the @post of the partial, so when it goes to evaluate the partial it gets a null reference.

Alternately, ensure that your post fetching functions are actually returning something


I'm not positive, but I think in the partial you have to do post.title not @post.title

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜