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?
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?
Try this:
<% @posts.each do |post| %>
<%= render 'middle', :post => post %>
<% end %>
Like this you'll have a local variable post available within the partial.
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' %>
<%= 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.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