Home > other >  Create multiple records using strong params
Create multiple records using strong params

Time:06-27

I'm newbie to Ruby/Rails world and I have the following problem that I'm struggle to make it work.

I have the following sample structure of json data which I'm trying to save in database.

{ "new_contacts"=>
[{"given_name"=>"John", "family_name"=>"Doe", "cell"=>"123456", "country_code"=>"IT"}, 
{"given_name"=>"Sara", "family_name"=>"Peti", "cell"=>"221214", "country_code"=>"IT"}] }

Now inside my controller I have the following code to process this json data and try to save them.

def multi_create
  results =  @contact_book.contacts.create(new_contacts_params)
end
  
def new_contacts_params
  params.require(:new_contacts).permit([ :given_name, :family_name, :cell, :country_code ])
end

I have tried many combinations but with no luck. Can anyone help me please.

Thanks in advance

CodePudding user response:

To permit nested keys in array and require parent key you can use

params
  .permit(new_contacts: %i[given_name family_name cell country_code])
  .require(:new_contacts)
  • Related