Omitting iterative processing using render's collection option

Operating environment Ruby 2.6.5 Rails 6.0.3.2

I learned that if you want to iterate over a partial template called by render by using collection, you can omit it, so I posted it.

When not using collection

ruby:index.html.erb


<% @hoges.each do |hoge| %>
  <%= render partial: "huga", locals: {hoge: hoge} %>
<% end %>

The above code calls the partial template huga, passes a variable called hoge in it, and repeats the process. Let's see what happens when we use collection.

When using collection

ruby:index.html.erb


<%= render partial: "huga", collection: @hoges %>

This code has the exact same meaning ** as the previous code. You'll find that it's very easy to write because you only need one line of three lines of code. Please note that if you write @hoge or @hoges in the partial template huga, an error will occur. @Hoges after the collection is an instance variable received from the controller. In fact, the variable you are passing to the partial template is the same hoge as the code above, so be careful.

Suddenly a collection came out with the render option and I've been confused, so I hope this article helps.

Recommended Posts

Omitting iterative processing using render's collection option
Iterative processing
[Ruby] Iterative processing
Ruby Iterative Processing
java iterative processing