Sambhav Sharma
Sambhav Sharma

Reputation: 5860

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?

Upvotes: 3

Views: 1034

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

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 :)

Upvotes: 2

Related Questions