Question

I'm still trying to wrap my head around Strong Parameters in Rails 4. I'm getting an ActiveModel::ForbiddenAttributesError when trying to submit a form with params for another model that it belongs_to.

Product :has_many DiskFiles

After some sleuthing I realize that I need to symbolize my keys before passing them into something like this otherwise I'll get the ForbiddenAttributesError. So this will work:

#disk_files_controller.rb
def update
     product = @disk_file.create_product(params[:product].symbolize_keys) if params[:product]
    ...
end

inspecting params[:product]:

>> params[:product]
=> {"title"=>"Registration Test5", "year"=>"1988", "region_id"=>"7"}

in either case I'm permitting these params (among others):

def disk_file_params
  params.require(:disk_file).permit(:filename, :file_path, :title,
                                    :product, :year, :region_id)
end

Being as all params are initially strings then should we be permitting the string version of the params instead of the symbol?!? Not sure what's best practice here?!? I know the Rails 4 templates include the symbolized parameters.

Was it helpful?

Solution

  1. No need to manually call #symbolize_keys. rails does this for you.
  2. you can use nested attributes in StrongParams this way

    params.require(:model_name_here).permit(:attribute1, :attribute2, :attribute3, nested_model_name_here: [:attribute1, :attribute2, :attribute3])

so you can do something like this:

params.require(:product).permit(:title, :year, :region_id, disk_file: [:filename, :file_path, :title,
                                :product, :year, :region_id])

This is assuming that disk_file's attributes is nested inside product for params hash. If you still get an error, please post a dummy app on github which reproduces this behaviour. so I can help you further. Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top