How to use Rails 4 strong parameters with has_many :through association?

百般思念 提交于 2019-11-28 04:30:53

Keep in mind that the name you give to your strong parameters (employees, employee_ids, etc.) is largely irrelevant because it depends on the name you choose to submit. Strong parameters work no "magic" based upon naming conventions.

The reason https://gist.github.com/leemcalilly/a71981da605187d46d96 is throwing an "Unpermitted parameter" error on 'employee_ids' is because it is expecting an array of scalar values, per https://github.com/rails/strong_parameters#nested-parameters, not just a scalar value.

# If instead of:
... "employee_ids" => "1" ...
# You had:
... "employee_ids" => ["1"]

Then your strong parameters would work, specifically:

... { :employee_ids => [] } ...

Because it is receiving an array of scalar values instead of just a scalar value.

Ok, so I actually did not need to nest the parameters. This is what ended up working for me:

# Never trust parameters from the scary internet, only allow the white list through.
def checkout_params
  params.require(:checkout).permit(:job, :shift, :employee_ids, :date, :hours, :sales, :tips, :owed, :collected, :notes)
end

Here is the combination of changes that worked.

Still not quite understanding why this worked though.

I can post the permit statement I use in one of my controllers. This has a many to many association as well. You nest the permit array. Use the lookup association in your permit statement. The only difference should be that yours won't be nested a third time.

In my case, the association Quote has_many :quote_items.

QuoteItems has_many :quote_options, :through => quote_item_quote_options.

In quotes_controller.rb

params.require(:quote).permit(:quote_date, :good_through, :quote_number, quote_items_attributes: [:id,:quote_id, :item_name, :material_id, quote_item_quote_options_attributes:[:quote_option_id,:quote_item_id,:qty,:_destroy,:id]])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!