【パーシャル】:collectionオプションによる複数オブジェクトのレンダリング
パーシャルにオブジェクトの複数形を渡し、見やすいコードにする
基本の使い方
collectionオプションにより、コレクションのメンバごとにパーシャルをレンダリングする
<%= render partial: "product", collection: @products %>
具体的な使い方
Before Refactor
<ul> <% @users.each do |user| %> <li> <%= link_to user.name, user %> </li> <% end %> </ul>
After Refactor
<ul> <%= render partial: "user", collection: @users %> </ul>
_user.html.erb
<li> <%= link_to user.name, user %> </li>
パーシャルにおいて、ローカル変数の名称を変更したい
パーシャル側で :collection オプションで渡されたオブジェクトに好きな名称を付けたい場合は :as オプション を使う
<ul> <%= render partial: "user", collection: @users, as: :owner %> </ul>
上記により、パーシャルにおいて変数 owner で user オブジェクトを扱えるようになる。
_user.html.erb
<li> <%= link_to owner.name, owner %> </li>