Bad_Pan
Bad_Pan

Reputation: 508

Create multiple records using strong params

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

Upvotes: 1

Views: 214

Answers (1)

mechnicov
mechnicov

Reputation: 15248

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)

Upvotes: 2

Related Questions