I currently have a form where I need to remove some fields from the params in the controller before it is saved (there are no columns for the fields, they are used only to populate linked selects).
The problem is this: I get a mass assignment error for the fields that should not be sent before I have a chance to remove them. I was of the understanding that the error would only fire when the controller gets to @sale = Sale.new(params[:sale]) but it seems to be occurring before that (I put line at the very start of the controller below, puts "sale params: " + params[:sale].to_s but it does not fire, only the mass assignment error occurs.
My controller create action code looks like:
def create
puts "sale params: " + params[:sale].to_s
params[:sale] = params[:sale].except([:vehicles_attributes])
@sale = Sale.new(params[:sale])
if @sale.save
redirect_to @sale, :notice => "Successfully created address."
else
render :action => 'new'
end
end
How can I ensure that the :vehicles_attributes hash is removed from params before I get the mass assignment error?
EDIT: Full error, as requested:
ActiveModel::MassAssignmentSecurity::Error in SalesController#create
Can't mass-assign protected attributes: make, model
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"LX/uEp5o9smc3sCcjQbOXQQgaK2wihvS0OPZTdNOj6w=",
"sale"=>{
"sale_type_id"=>"1",
"date"=>"",
"customer_attributes"=>{
"customer_type_id"=>"1",
"emails_attributes"=>{
"0"=>{
"value"=>""}}},
"vehicles_attributes"=>{
"0"=>{
"make"=>"4",
"model"=>"38",
"trim_id"=>"658",
"model_year_id"=>"12"
}}}}
Make and Model are the attributes I am trying to remove when I am doing params[:sale] = params[:sale].except([:vehicles_attributes]) (they are in the :vehicles_attributes hash, as you can see from the error).
After a LOT of investigating, it turned out that I was unable to remove the parameters from the hash before the error because the
createmethod was being overridden by the Cancan gem (when I didload_and_authorize_resources.Removing this solved the problem, when using the code from Frederick Cheung.