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?
A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With