1
1

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.

render partial collection、値が入らない

Last updated at Posted at 2019-03-26

この記事は配列に入った値を部分テンプレートのキーに繰り返し当てていくpartialのcollectionオプションに関してハマった記事が見つからなかったので無かったのでメモします。
(そもそもcollectionオプションの記事が少なかった)

collectionを使用する経緯

そもそもですが、each文でも繰り返しrenderさせることはできますが、なぜcollectionかというところで、パフォーマンスがcollectionの方が良いとのことでcollectionを使い配列の情報を部分テンプレートに繰り返し表示させようと思い使用しました。

参考記事
https://qiita.com/itmammoth/items/612efc6ad3280349b7e1

render partialのcollectionオプションの使いかたに関して事前知識

パーシャルはデータの繰り返し (コレクション) を出力する場合にもきわめて便利です。:collectionオプションを使用してパーシャルにコレクションを渡すと、コレクションのメンバごとにパーシャルがレンダリングされて挿入されます。

参考記事 3.4.5 コレクションをレンダリングする
https://railsguides.jp/layouts_and_rendering.html

問題点

値は部分テンプレートの #{item.name}に値が入っていかない。

hoge.haml
.item-box
 = render partial: 'item-box', collection: @item
_item-box.haml
.item-box_item-name
  #{item.name}

確認

_item-box.hamlにbinding.pryを行い、
item.nameで値が取り出せることは確認済み。
だが入らない、なぜ。

下記の記事を参考させていただき、変数の渡し方が少し変化球で動くようだと言うことがわかりました。
https://qiita.com/bambis13s/items/015f5bf921eb820ef652


<引用>
collectionで渡すと勝手にeachして、asで指定した変数に入れてくれます。
ちなみにcollectionは何も指定しないと、eachされた変数は参照先テンプレートの名前になります。


なるほど。つまりas: :キー、この場合で言うと部分テンプレート先に渡る際のキー名をas: :itemと変数定義することでいいのか、ということで下記に更新。

hoge.haml
 = render partial: 'show-box', collection: @item, as: :item

結果

as:でキーの変数を定義することで部分テンプレートにparams内の値がきちんと入ってくれました。

追記


<引用>
どこを修正してもエラーがなおらない!!
同じ部分テンプレートを別の場所でもrenderしていないか?
そんな時は別の場所で同じ部分テンプレートをrenderしている可能性あり


以上、参考になれば幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?