Help us understand the problem. What is going on with this article?

railsでパーシャルに引数が渡らないときはcocoonが関係しているかも

パーシャルに引数が渡らない

※ cocoonを使用している場合しか以下は参考になりません。

例えば以下のような構成だとします。
必要最低限しか書いていません。

  • パーシャル呼び出し側
.cocoon-container
  = f.fields_for :form_items do |form_item|
    = render 'partial', f: form_item, partial_arg: 'パーシャルに渡す引数'
  .add_button
    = link_to_add_association '追加ボタン',
      f,
      :form_items,
  • パーシャル
.nested-fields
  .field
    = link_to_remove_association '削除ボタン', f
/ ここら辺で partial_arg を参照するとなぜか undefined local value になる

なぜかパーシャルで partial_argを参照するとundefinedになります。

解決方法

パーシャル呼び出し側の追加ボタンにオプションを足してあげるといけます!

.cocoon-container
  = f.fields_for :form_items do |form_item|
    = render 'partial', f: form_item
  .add_button
    = link_to_add_association '追加ボタン',
      f,
      :form_items,
      render_options: {locals: { partial_arg: 'パーシャルに渡す引数' }}

render_options: {locals: { partial_arg: 'パーシャルに渡す引数' }}のところです!
もちろん、partial_argは好きな名前で大丈夫です!

以上!

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away