Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails strong params for creating multiple objects from one form

I am trying to create multiple objects of the same model from one form. Params which I get in my create method look like this:

<ActionController::Parameters {"objects"=> <ActionController::Parameters {
  "0"=>{priority"=>"24", "style"=>"three_pictures"}, 
  "1"=>{"priority"=>"24", "style"=>"three_pictures"}, 
  "2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false>}permitted: false>

I am confused about using strong params in this case. My create method looks like this:

def create
  params[:objects].each do |index, object|
    Object.create(object.permit(:priority, :style))
  end
  ...
end

This works, but doesn't look like the right way to do this. How should this be done?

like image 269
Sambhav Sharma Avatar asked Feb 13 '26 03:02

Sambhav Sharma


1 Answers

I think that I need a bit more info here. When I create more than 1 record at a time its usually a chield of another object and mine looks like this

# Never trust parameters from the scary internet, only allow the white list through.
def family_params
  params.require(:family).permit(:name, users_attributes: [ :name, :email ])
end

I hope that this helps.

Happy Hacking :)

like image 160
MZaragoza Avatar answered Feb 14 '26 17:02

MZaragoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!