I think it's common to use each in a view template, such as when displaying an index.
Rails has a method that allows you to display the same element multiple times using a partial template without having to write each.
As an example, consider the case where the user is displayed as a table. If you have a controller like the one below
users_controller.rb
def index
@users = User.all
end
You can use each to generate a table as follows:
erb:index.html.erb
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
</tr>
<% end %>
You can use the render method to represent iterations using partial partials.
erb:index.html.erb
<%= render partial: "user", collection: @users %>
Prepare a partial partial.
erb:_user.html.erb
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
</tr>
If you specify a collection in the collection option of the render method, the number of elements and the partial partial will be embedded in this position. Local variables in partial partials are named after the partial's name.
If you rename the partial to client
<%= render partial: "client", collection: @users %>
The local variable in the partial partial is client.
erb:_client.html.erb
<tr>
<td><%= client.name %></td>
<td><%= client.email %></td>
</tr>
Note that it is not the singular form of the variable specified in the collection. Also, when adding the collection option, partial cannot be omitted.
erb:index.html.erb
<% @users.each do |user| %>
<%= render "user", user: user %>
<% end %>
erb:_user.html.erb
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
</tr>
Repeated display of partial templates without using a collection will result in poor performance. When calling the partial template repeatedly, use the collection option.
erb:index.html.erb
<%= render @users %>
erb:_user.html.erb
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
</tr>
If you pass a collection as an argument of the render method, the partial name will be inferred from the model name of the element.
The author of this article is a beginner just starting to learn programming. I would appreciate it if you could point out any mistakes.
reference Performance notes when rendering partials [Rails Guide](https://railsguides.jp/layouts_and_rendering.html#%E3%83%91%E3%83%BC%E3%82%B7%E3%83%A3%E3%83%AB%E3% 82% 92% E4% BD% BF% E7% 94% A8% E3% 81% 99% E3% 82% 8B)
Recommended Posts