大家好,我在 rails4 里试着用了下 nested form,两个 model 分别是 item 和 tag,
item has_many tags
items_controller 里加了 tags 的白名单:
private
# Use callbacks to share common setup or constraints between actions.
def set_item
@item = Item.find(params[:id])
@item.tags.build
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
params.require(:item).permit(:name, :description, :price, :shopping_list_id, tags_attributes: [:name, :item_id])
end
item 的 form 里加了个 fileds_for tags:
_form.html.erb
<%= f.fields_for :tags do |tag_form| %>
<div class="field">
<%= tag_form.label :name, 'Tag:' %>
<%= tag_form.text_field :name %>
</div>
<% unless tag_form.object.nil? || tag_form.object.new_record? %>
<div class="field">
<%= tag_form.label :_destroy, 'Remove:' %>
<%= tag_form.check_box :_destroy %>
</div>
<% end %>
<% end %>
可是当 update item 的时候,只填写一个 tag 却插入 db 里面 2 个,请看控制台输出:
Started PATCH "/items/1" for 127.0.0.1 at 2013-03-01 17:01:09 +0800
Processing by ItemsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"v+V8G8Cu6uUUWIH8PTYO89fOcQDiIA7gSYLkbjygunY=", "item"=>{"name"=>"mac book pro", "description"=>"rMBP", "price"=>"9999.99", "shopping_list_id"=>"1", "tags_attributes"=>{"0"=>{"name"=>"22"}}}, "commit"=>"Update Item", "id"=>"1"}
Item Load (0.3ms) SELECT `items`.* FROM `items` WHERE `items`.`id` = 1 LIMIT 1
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `tags` (`created_at`, `item_id`, `updated_at`) VALUES ('2013-03-01 09:01:09', 1, '2013-03-01 09:01:09')
SQL (0.2ms) INSERT INTO `tags` (`created_at`, `item_id`, `name`, `updated_at`) VALUES ('2013-03-01 09:01:09', 1, '22', '2013-03-01 09:01:09')
(10.5ms) COMMIT
Redirected to http://localhost:3000/items/1
而且插入的第 1 条数据里面没有 tag name,求助大家有没有遇到过类似情况?