How to use strong parameters with an objects array in Rails

Johan S picture Johan S · Sep 3, 2013 · Viewed 8.4k times · Source

When using Rails 4.0 strong parameters, how do I permit JSON like this?

{
   "user":
   {
       "first_name":"Jello"
   },
   "users_to_employer":[
       {
           "start_date":"2013-09-03T16:45:27+02:00",
           "end_date":"2013-09-10T16:45:27+02:00",
           "employer":{"company_name":"Telenor"}
       },
       {
           "start_date":"2013-09-17T16:45:27+02:00",
           "end_date":null,
           "employer":{"company_name":"Erixon"}
       }
   ]
}

I tried:

 params.require(:users_to_employers => []).permit(
                                                 :start_date, 
                                                 :end_date => nil,
                                                 :employer => [
                                                     :company_name
                                                 ])

But it didn't work.

Answer

Mike Szyndel picture Mike Szyndel · Sep 3, 2013

To accept an array of objects, put the params in an array:

params.permit(
  users_to_employers: [
    :start_date,
    :end_date,
    employer: [ :company_name ]
  ]
)