Rails 允许嵌套哈希参数

Rails permit nested hash parameters

这是我的参数:

{"utf8"=>"✓", "authenticity_token"=>"g0mNoBytyd0m4oBGjeG3274gkE5kyE3aPbsgtqz3Nk4=", "commit"=>"Save changes", "plan_date"=>{"24"=>{"recipe_id"=>"12"}, "25"=>{"recipe_id"=>"3"}, "26"=>{"recipe_id"=>"9"}}}

我如何允许:

"plan_date"=>{"24"=>{"recipe_id"=>"12"}, "25"=>{"recipe_id"=>"3"}, "26"=>{"recipe_id"=>"9"}}

要获得如下所示的输出:

permitted_params = ["24"=>{"recipe_id"=>"12"}, "25"=>{"recipe_id"=>"3"}, "26"=>{"recipe_id"=>"9"}]

这样我就可以使用以下内容来保存:

permitted_params.each do |id, attributes|
  Object.find_by_id(id.to_i)
  Object.update_attributes(attributes)
end

我正在尝试以下方法,但它不起作用:

def permitted_params
  params.require(:plan_date).permit(:id => [:recipe_id])
end

事实上,我的版本没有让任何事情通过 =(

Hashes with integer keys are treated differently and you can declare the attributes as if they were direct children

RailsGuides - Action Controller Overview

def permitted_params
  params.require(:plan_date).permit([:recipe_id])
end

虽然"Rails Way"是用fields_for.

<%= form_for :plan_date do |f| %>
  <%= f.fields_for :recipes do |ff| %>
    <%= ff.text_field :foo %>
  <% end %>
<% end %>

这为您提供了一个嵌套的属性散列:

plan_date: {
  recipes_attributes: [
    "0" => { foo: 'bar' } 
  ]
}

可以与 accepts_nested_attributes_for 一起使用来创建和更新嵌套模型。

def update
  @plan_date.update(permitted_params)
end

def permitted_params
  params.permit(:plan_date).permit(recipies_attributes: [:foo])
end