Pass a variable into a partial, rails 3?

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try this:

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

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

Solution 2 - Ruby on-Rails

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' %>

Solution 3 - Ruby on-Rails

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

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

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElliotView Question on Stackoverflow
Solution 1 - Ruby on-RailspolarblauView Answer on Stackoverflow
Solution 2 - Ruby on-RailsStefaan ColmanView Answer on Stackoverflow
Solution 3 - Ruby on-RailsFelix AndersenView Answer on Stackoverflow
Solution 4 - Ruby on-RailssevenseacatView Answer on Stackoverflow
Solution 5 - Ruby on-RailsfatfrogView Answer on Stackoverflow