1

私はレールを初めて使用し、jquery を使用して独自の動的フィールドを実装しようとしています。フォームにフィールドを追加しても問題ありませんが、パラメーターが希望どおりに送信されません。これが私のjQueryです:

$('form').on('click', '#add_ingredient', function(){
    count = 1;
    field = $('#ingredient_list li').first()
        .clone()
            .find('input')
                .val('')
                    .end()
                        .find('input')
                            .prop({id: 'entry_ingredients_attributes_' + count + '_name', name: 'entry[ingredients_attributes][' + count +'][name]'  })
                                .end();
    $('#ingredient_list').append(field);
    count += 1;
})

これにより、複数のリスト項目を追加でき、それらの ID と名前がインクリメントされて一意になるようになります。

モデルが正しくセットアップされ、accepts_nested_attributes_for を使用できるようになりました。モデル Entry、Ingredient、および関連付け EntryIngredient を持つベーキング ジャーナルを作成しています。私の問題は次のとおりです。

フォームを送信すると、複数のフィールドを追加した場合でも、最後の 1 つだけが送信されます。これは、1 つ以上の成分を含むフォームを送信したときのパラメーターの出力です。

"ingredients_attributes"=>{"0"=>{"name"=>"Flour", "_destroy"=>"false"}, "1"=>{"name"=>""}}}}

これがどのように作成されているかを知りたい場合のために、私のフォームも示します。

  <div id="ingredients">
      <%= f.fields_for :ingredients, @entry.ingredients.build do |builder| %>
      <%= render 'ingredient_fields', :f => builder %>
      <% end %>
  </div>
  <div id='add_ingredient'>Add Ingredient</div>
  <div class="actions">
    <%= f.submit %>

#_ingredient_fields
<ul id="ingredient_list">
    <li>
      <%= f.label :name %>
      <%= f.text_field :name %>
      <%= f.hidden_field :_destroy %>
      <%= link_to "Remove", "#", :class => "remove_fields" %>
    </li>
</ul>

誰かが私を正しい方向に向けることができますか?


解決

以下の回答での Zaid Crouch の提案に従って、私のセレクターが正しいことをしていないことが判明しました。私のJSは次のようになりました:

$('form').on('click', '#add_ingredient', function(){
    count = $('#ingredient_list li').length;
    field = $('#ingredient_list li').first()
        .clone()
            .find('input')
                .val('')
                    .end()
                        .find('input :first')
                            .prop({id: 'entry_ingredients_attributes_' + count + '_name', name: 'entry[ingredients_attributes][' + count +'][name]'  })
                                .end()
                                    .find('input :last')
                                        .prop({id: 'entry_ingredients_attributes_' + count + '__destroy', name: 'entry[ingredients_attributes][' + count +'][_destroy]', value: 'false'  })
                                            .end();
    $('#ingredient_list').append(field);
})

これらの要素を選択するためのより良い方法を誰かが推奨できる場合は、プロパティを変更しています。フィードバックをいただければ幸いです。

4

1 に答える 1

3

送信された最後の値のみを取得している場合、それはおそらく重複した入力があるという良いヒントですnames。.js によって追加された html を (firebug または webkit インスペクタを使用して) 検査することで、これが発生していることを確認できるはずです。

関数を見ると、関数count内で変数を初期化しています。関数が返されると、スコープ外になるため、関数が呼び出されるたびに が使用されますcount = 1。変更することでこれを修正できるはずです

count = 1;

count = $('#ingredient_list li').length;

(何もしないので、関数の最後にインクリメントを取り除くこともできます)。

_destroyまた、隠しフィールドの名前と ID も更新する必要があります。

于 2013-03-17T23:07:04.873 に答える