ruby-on-rails has_one关联的嵌套属性

js4nwp54  于 12个月前  发布在  Ruby
关注(0)|答案(5)|浏览(83)

我需要为在新建和编辑操作中具有一个关联的属性设置,因此我有以下内容:
产品型号

has_one :store
accepts_nested_attributes_for :store

字符串
形成

= form_tag @product do |f|
  = f.fields_for :store do |store_fields|
    = render 'store_form', :f => store_fields


在控制器中
参数。必需(:存储)。允许(:存储)。允许!
字段,但当我提交表单时,它没有意义,存储关联为空问题怎么能解决呢?

统一产品开发部

params.require(:product).permit(store_attributes: [:store_id, :supplier_id, :margin, :discount]).permit!


日志:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "product"=>{"name"=>"qwefqwefasdf", "description"=>"", "permalink"=>"asdf", "store_attributes"=>{"margin"=>"123", "discount"=>"123"}}, "button"=>"", "id"=>"asdf"}

llmtgqce

llmtgqce1#

好吧,正确的答案是
变化

= f.fields_for :store do |store_fields|

字符串

= f.fields_for :store, @vendor.store do |store_fields|

qoefvg9y

qoefvg9y2#

确保发送所需参数。(勾选复数)

你能从服务器端复制和粘贴参数吗?

13:44:29 INFO:   Parameters: {"utf8"=>"✓" .......

字符串
这将有助于正确地命名参数
如果参数命名正确,但未被接受,则尝试显式指定它们

params.permit(:product => [:something, :stores_attributes => [:name, :address ]])

更新:

params.permit(:product => [ :name, :description, :permalink, :store_attributes => [:store_id, :supplier_id, :margin, :discount]])

嵌套属性示例:

http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

8yparm6h

8yparm6h3#

查看控制台中的参数。您应该看到类似以下内容:

{ "product" => { "store_attributes" => {  } }

字符串
这意味着您需要require:product(您需要产品参数)并允许商店的正确属性。

params.require(:product).permit(:store_attributes => [ :name, :location, :etc ])


当你需要(:store)时,这意味着你希望在参数散列的根处有一个“store”键,但事实并非如此(以及为什么你的关联是空的)。

vktxenjb

vktxenjb4#

假设所讨论的控制器是ProductsController,则强参数定义是不正确的。
试试看:

params.require(:product).permit(:store_attributes)

字符串
或者,更严格地说,只允许必需的属性:

params.require(:product).permit(store_attributes: [ :store_field1, :store_field2 ])


其中,:store_field1:store_field2store模型中的属性,这些属性位于form中,并且您希望允许。

更新:

以下操作应根据日志输出工作。

params.require(:product).permit(:name, :description, :permalink, store_attributes: [ :margin, :discount ])

wlwcrazw

wlwcrazw5#

不行不行。如果你使用nested_attributes和has_one关联,这些属性应该写在普通的,而不是单独的数组中。

相关问题