14

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.

2
  • 1
    try params.permit(users_to_employers: [{ :start_date, :end_date, employer: { :company_name }]) Commented Sep 3, 2013 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 "How to Ask" and the linked pages for more information. Commented Mar 23, 2020 at 21:27

1 Answer 1

35

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

params.permit(
  users_to_employers: [
    :start_date,
    :end_date,
    employer: [ :company_name ]
  ]
)
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I updated the answer. I didn't really test that, just knew how it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.