Rails nested form error in rails 4

young4u_amy · 2013年03月01日 · 最后由 doitian 回复于 2013年03月01日 · 2333 次阅读

大家好,我在rails4里试着用了下nested form,两个model分别是 item 和 tag, item has_many tags


  # Use callbacks to share common setup or constraints between actions.
  def set_item
    @item = Item.find(params[:id])     

  # 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])

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 %>
      <% unless tag_form.object.nil? || tag_form.object.new_record? %>
        <div class="field">
          <%= tag_form.label :_destroy, 'Remove:' %>
          <%= tag_form.check_box :_destroy %>
      <% end %>
    <% end %>

可是当update item的时候,只填写一个tag却插入db里面2个,请看控制台输出:

Started PATCH "/items/1" for 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, 求助大家有没有遇到过类似情况?

共收到 3 条回复


你是不是在哪 build 了个 new tag 做占位符?

果然,在 create 里 save 之前不要去调用 set_item.tags.build

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册