我有一个嵌套形式,其中还有另一个。基本上我拥有的是一堆成分,对于每种成分,我都有一个数量和单位,它存储在条目和成分之间的关联表中,称为 EntryIngredient。使用我的以下 JS,我可以添加动态字段,但是当我提交时,我收到 AssociationTypeMismatch 错误。不知道为什么,参数对我来说看起来不错("ingredients_attributes"=>{"0"=>{"name"=>"Salt", "entry_ingredients"=>{"quantity"=>"2.5", "unit"=>"tbspns"}, "_destroy"=>""}}}}
),我错过了什么?实际上,我认为这可能是因为它发送 asentry_ingredients
而不是entry_ingredients_attributes
,但我看不出我在第二个嵌套形式中做了什么不同。这是具有成分字段的第一个表单:
<div id="ingredients">
<p>Ingredient List:</p>
<%= 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 %>
这是 entry_ingredients 的代码:
<ul id="ingredient_list">
<li>
<%= f.label :name %>
<%= f.text_field :name, :class => "ingredient_field" %>
<%= f.hidden_field :_destroy, :class => "delete_ingredient" %>
<%= f.fields_for :entry_ingredients, @entry.entry_ingredients.build do |builder| %>
<%= render 'entry_ingredient_fields', :f => builder %>
<% end %>
<%= link_to "Remove", "#", :class => "remove_fields" %>
</li>
</ul>
继承人我的 JS 用于动态添加新成分:
$('form').on('click', '#add_ingredient', function(){
count = $('#ingredient_list li').length;
field = $('#ingredient_list li').first()
.clone() //clone the first element in the list
.find('input') //find all its inputs
.val('') //set all input values to blank
.end()
.find($('.ingredient_field'))
.prop({id: 'entry_ingredients_attributes_' + count + '_name', name: 'entry[ingredients_attributes][' + count +'][name]' })
.end()
.find($('.delete_ingredient'))
.prop({id: 'entry_ingredients_attributes_' + count + '__destroy', name: 'entry[ingredients_attributes][' + count +'][_destroy]', value: 'false' })
.end()
.find($('.ingredient_quantity'))
.prop({id: 'entry_ingredients_attributes_' + count + '_entry_ingredients_quantity', name: 'entry[ingredients_attributes][' + count +'][entry_ingredients][quantity]'})
.end()
.find($('.ingredient_unit'))
.prop({id: 'entry_ingredients_attributes_' + count + '_entry_ingredients_unit', name: 'entry[ingredients_attributes][' + count +'][entry_ingredients][unit]'})
.end();
$('#ingredient_list').append(field);
})