4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでrenderとcollectionを使う

Posted at

初めに

Controllrからの値を割り振る際にeachを使って下記のように割り振ることがあると思います。

views/_xxx.html.erb

<% @users.each do |user| %>
  <ul class="lists">
    <li class="list">#{user.name}</li>
  </ul>
<% end %>

Viewでの繰り返し部分を、eachメソッドを使用するのではなく、コレクションをレンダリングすることで実装する方法が綺麗になると思い以下のように私は書きます。

Collection

views/yyy.html.erb

<ul class="lists">
  <%= render partial: "user", collection: @users %>
</ul>
_user.html.erb

<li class="list">#{user.name}</li>

また、asで自分が指定したいローカル変数名に書き換えることも可能です。

views/yyy.html.erb
<ul class="lists">
  <%= render partial: "user", collection: @users, as: :person %>
</ul>
_user.html.erb

<li class="list">#{person.name}</li>
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?