141

I have a loop like such:

<% @posts.each do |post| %>
  <% render middle %>
<% end %>

Then in my middle partial, how do I access the current post?

1
  • Hello Elliot I'm using this on standard scaffolded. Using inside index.html.erb to render _show.html.erb where show partial contains modal. every thing is working fine except that when I press show link, it is showing same id instead of showing different id's. Commented May 3, 2015 at 4:23

5 Answers 5

236

Try this:

<% @posts.each do |post| %>
  <%= render 'middle', :post => post %>
<% end %>

Like this you'll have a local variable post available within the partial.

Sign up to request clarification or add additional context in comments.

2 Comments

you need <%= %> not <% %> tags or else it will not render
Keep in mind, you would need <%= render 'middle', :post => post %> for rails 3.1.x
124

Give it to the partial as a local variable

<%= render :partial => 'middle', :locals => { :post => post } %>

Of course, rails also has a shortcut for rendering collections:

<%= render :partial => 'post', :collection => @posts %>

In this case it will call the partial post for every post with a local variable 'post'

You can even render a spacer template between each post:

<%= render :partial => 'post', :collection => @posts, :spacer_template => 'post_divider' %>

4 Comments

Didn't know about the :spacer_template option, really nice. Thanks!
Note that the :locals hash is not needed when using Rails 3. The arguments hash is converted into arguments which are passed to the partial.
I still needed :locals hash for it to work.. I'm running 3.2.12
<%= render :partial => 'post', :collection => @posts, as: :post %> will automatically loop through each post in your partial, so you can use post in your partial as the variable.
14
<% @posts.each do |post| %>
  <% render middle, :post => post %>
<% end %>

You can now access post as the local variable post in the partial

Comments

10

Replace <%= render middle %> with <%= render middle, :post => post %>. Then in your middle partial, you can access the post variable.

Comments

0

You can replace the entire each block with this:

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

Or even shorter:

<%= render @posts %>

Full documentation (section 3.2) https://guides.rubyonrails.org/action_view_overview.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.