在Controller中,我正在尝试访问深度嵌套的参数。这是我的参数跟踪。
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"2j+Nh5C7jPkNOsQnWoA0wtG/vWxLMpyKt6aiC2UmxgY=",
"inventory"=>{"ingredients_attributes"=>{"0"=>{"ingredient_name"=>"Bread"}},
"purchase_date"=>"11",
"purchase_price"=>"11",
"quantity_bought"=>"11"},
"commit"=>"Create Inventory"}
我正试图从中检索“面包”。我尝试了params[:inventory][:ingredient][:ingredient_name]
和其他变体。什么是正确的styntax?
如果重要,
Inventory has_many :ingredients
Inventory accepts_nested_attributes_for :inventories
谢谢!
答案 0 :(得分:1)
直接访问值“面包”的字面意思是:
params[:inventory][:ingredients_attributes]["0"][:ingredient_name]
我打赌你不想这样做。
使用accepts_nested_attributes_for
和哈希结构(也假设成分属性设置正确),您可以在库存实例上设置参数,并将值“Bread”设置为其中一个协会中的成分对象:
@inventory = Inventory.new(params[:inventory])
# or @inventory.attributes = params[:inventory] for an existing
# inventory instance
ingredient = @inventory.ingredients.first
ingredient.ingredient_name
# => "Bread"