Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
cbrulak Avatar asked Oct 08 '09 19:10

cbrulak


People also ask

What is the reason for having partials in Rails?

A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts.

How can you tell Rails to render without a layout *?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.

How do you use nested layouts Rails?

Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.


1 Answers

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.

like image 87
EmFi Avatar answered Oct 13 '22 11:10

EmFi