Exclusion of nested form fields in controller action using Hash # exception before generating mass_assignment error?

I currently have a create action in a sales controller that looks like this:

def create @sale = Sale.new(params[:sale].except(:vehicles_attributes)) if @sale.save redirect_to @sale, :notice => "Successfully created sale." else render :action => 'new' end end 

The goal is to exclude a couple of attributes that are only used to populate related samples and should not be sent (there are no columns for them).

With the controller code above, I found that the parameters still contain "sale"=>{"vehicles_attributes"=>{"0"=>{"make"=>"","model"=>""}}} , so it seems that I missed something in the controller code.

EDIT: after some additional searching, I found that the mass_assignment exception was thrown before my code, except for the code, was able to remove the parameters that should not be submitted by the form, so I will go back to the square.

How can I make sure that I delete fields that should not be submitted by the form before I get the mass_assignment error?

0
source share
1 answer

As far as I know, when calling new , a mass_assignment error should occur, so your path should work. Although I never used the except method. Have you tried using the reject! method reject! ?

 def create params[:sale].reject! { |k, v| k == :vehicles_attributes } @sale = Sale.new(params[:sale]) if @sale.save redirect_to @sale, :notice => "Successfully created sale." else render :action => 'new' end end 

If you need to save :vehicles_attributes , you can also use the reject method (without interruption), which gives you a copy instead of removing it from the original hash.

+1
source

Source: https://habr.com/ru/post/924274/


All Articles