13

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Johan S
  • 3,531
  • 6
  • 35
  • 63
  • 1
    try params.permit(users_to_employers: [{ :start_date, :end_date, employer: { :company_name }]) – Mike Szyndel Sep 03 '13 at 16:44
  • 1
    When asking, don't say things like "it didn't work." That tells us nothing. If you got an error, put that into the question. If you expected a different result than what you got, put the expectation and the actual result into the question. See "[ask]" and the linked pages for more information. – the Tin Man Mar 23 '20 at 21:27

1 Answers1

32

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

params.permit(
  users_to_employers: [
    :start_date,
    :end_date,
    employer: [ :company_name ]
  ]
)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63
  • My ruby works fine with `[]`but not with `{}`. It says it's a syntax error with `{}`, but I'm using the `{ :employer => [ :company_name] syntax. – Johan S Sep 03 '13 at 21:06
  • I updated the answer. I didn't really test that, just knew how it should work. – Mike Szyndel Sep 03 '13 at 21:14