0
0

More than 1 year has passed since last update.

renderにおけるオプション

Posted at

インターンで実務に入っていた時にcollectionとlocalsについて理解が浅かったので、まとめようとおもいます。
以下のような例を見てみましょう

localsオプション

books_controller.rb
def index
 @book = Book.find(params[:id])
end
index.html.erb
<%= render partial: "form", locals: { book: @book } %>
_form.html.erb
<p>本のタイトルは、<%= book.title %>です。</p>
<p>本の内容は、<%= book.content %>です。</p>

locals: { book: @book }の部分は、
index.html.erbファイル内の@bookを部分テンプレート先でbookという名前で使えるようにするよ、というのがlocalsオプションです。
実際に、_form.html.erb内では、bookという名前で使われていますね。

collectionオプション

books_controller.rb
def index
 @books = Books.all
end
index.html.erb
<%= render partial: "form", collection: @books %>
_form.html.erb
<p>本のタイトルは、<%= book.title %>です。</p>
<p>本の内容は、<%= book.content %>です。</p>

collectionオプションは、部分テンプレート先でeach処理があるときに使えるオプションです。
上記のように書くことで、collectionオプションに指定されている変数の要素分だけ部分テンプレートが繰り返し表示されます。
もしcollectionオプションを使わなかったら

_form.html.erb
@books.each do |book|
 <p>本のタイトルは、<%= book.title %>です。</p>
 <p>本の内容は、<%= book.content %>です。</p>
end

collectionを使うことで、スッキリ書けますし、collectionオプションを使う方が、each文より処理が高速なんです。

以上です。何か間違いがございましたら、ご教示いただけますと幸いです。

【参考資料】

0
0
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
0
0