🗂
collectionでrenderする
posts_controller.rb
def index
@posts = Post.all
end
コントローラから受け取った値を1つずつ表示したい
eachの場合
posts/index.html.erb
<% @posts.each do |post| %>
<%= render 'post', post: post %>
<% end %>
この書き方だと@postsの数だけパーシャルが呼び出される、つまりパフォーマンスが悪い
collectionを使った場合
posts/index.html.erb
<%= render partial: "post", collection: @posts %>
collectionで回すと、パーシャルが一度しか呼ばれない、つまりこっちの方がパフォーマンスがいい
collectionを使う場合は、partial
を省略できないので注意
パーシャルで使うローカル変数も指定できる
posts/index.html.erb
<%= render partial: "user", collection: @posts, as: :tweet %>
Discussion