0

Here are my params:

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

How do I permit:

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

To get an output that looks like:

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

So that I can use the following to save:

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

I'm trying the following, but it's not working:

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

My version in fact, isn't letting anything go through =(

james
  • 3,989
  • 8
  • 47
  • 102
  • I answered a similar question - hope this helps http://stackoverflow.com/questions/30894070/rails-4-permit-any-keys-in-the-hash/31033036#31033036. – steve klein Jul 16 '15 at 02:25

1 Answers1

0

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

Although the "Rails Way" is to use fields_for.

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

This gives you a nested attributes hash:

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

Which can be used with accepts_nested_attributes_for to create and update nested models.

def update
  @plan_date.update(permitted_params)
end

def permitted_params
  params.permit(:plan_date).permit(recipies_attributes: [:foo])
end
max
  • 96,212
  • 14
  • 104
  • 165