Rails 5嵌套表单不会创建子记录

时间:2017-08-17 22:36:20

标签: ruby-on-rails nested-forms nested-attributes has-many-through

我已经被困在这几个小时了。我不了解嵌套表单的方式以及如何使用“accept_nested_attributes_for'应该工作。

我有一个' form_for'我的新名单和一个' fields_for'它的list_items。这是list_items的fields_。

fields_for:list_items

https://pastebin.com/NxZWGeYj

现在,' list_item'是:通过 List的一部分has_many_through与用户' user_items'的关联。这个嵌套的表单应该从" user_item'提交信息。需要建立一个list_item'这将属于新列表。看起来好像我的子项目的参数没有交付...

Started POST "/list" for 127.0.0.1 at 2017-08-17 18:18:04 -0400
Processing by ListsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"203D1bpQZzKU9J0gyUPOvQNFbkxmREyDLmb4IdARaDNjVX5fqCydg5dUe/d2NgWocU6AFkC+hWl5QCpfu9GLqw==", "list"=>{"name"=>"", "list_items_attributes"=>{"0"=>{"user_item_id"=>"1", "quantity"=>"1"}, "1"=>{"user_item_id"=>"2", "quantity"=>"1"}, "2"=>{"quantity"=>"1"}, "3"=>{"quantity"=>"1"}, "4"=>{"quantity"=>"1"}, "5"=>{"quantity"=>"1"}, "6"=>{"quantity"=>"1"}, "7"=>{"quantity"=>"1"}, "8"=>{"quantity"=>"1"}}}, "commit"=>"Submit"}

而@list无法保存并弹出两条Flash错误消息:

["List items list must exist", "List items user item must exist"]

这告诉我,我的list_items不能正确构建,或者我的字段不是正确的......或者其他东西。老实说,我被卡住了。无论如何,这是我的列表控制器:

https://pastebin.com/kDZHQ6vB

和我的List模型:

https://pastebin.com/MTH8Yf2S

再次使用fields_for:list_items

https://pastebin.com/NxZWGeYj

我真的希望这是有道理的。感谢

更新

我在这个表单发送的参数中注意到的是我的嵌套params散列似乎是部分数组......?

"list_items_attributes"=>{"0"=>{"user_item_id"=>"1", "quantity"=>"1"}, "1"=>{"user_item_id"=>"2", "quantity"=>"1"}

这不会反映在我的list_params中,可能是问题......但仍然不确定解决方法是什么:

def list_params
  params.require(:list).permit(:name, list_items_attributes: {:user_item_id, :quantity})
end

0 个答案:

没有答案