Help us understand the problem. What is going on with this article?

[Rails] リファクタリング render collection

More than 1 year has passed since last update.

user一覧など、インスタンス変数をloopさせて表示させるようなviewをリファクタリングする。
まずpartialを切る。

app/views/users/index.erb
<% @users.each do |user| %>
 <%= render (partial: )user %> 
<% end %>
app/views/users/_user.html.erb
<div class="users-index-item">
 <div class="user-right">
   <%= link_to user.name, user_path(user) %>
 </div>
</div>

ここからさらにeachも省略できる。

app/views/users/index.erb
 <%= render @users %> 
app/views/users/_user.html.erb
<div class="users-index-item">
 <div class="user-right">
   <%= link_to user.name, user_path(user) %>
 </div>
</div>

railsが勝手に@usersのコレクションをpartialに渡してくれる。
上のはindex.html.erbは下の省略バージョン。↓

app/views/users/_user.html.erb
<%= render :partial => "user", :collection => @users %>
ozipi
rails->PHP(laravel)エンジニア
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away