【问题标题】:Rails permit nested hash parametersRails 允许嵌套散列参数
【发布时间】:2015-07-15 23:52:00
【问题描述】:

这是我的参数:

{"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

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

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 parameters parameter-passing strong-parameters


【解决方案1】:

具有整数键的散列被区别对待,你可以声明 属性就好像它们是直接孩子一样

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多