Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use strong parameters with an objects array in Rails

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.

like image 759
Johan S Avatar asked Sep 03 '13 14:09

Johan S


People also ask

What is the use of strong parameters in Rails?

Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.

What does params require do in Rails?

In Rails, strong params provide an interface for protecting attributes from the end-user assignment. We can specify required attributes and neglect unnecessary attributes to be used in the Active model mass assignment.

Why We Use Permit in Rails?

The permit method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model.

What are Rails params?

As you might have guessed, params is an alias for the parameters method. params comes from ActionController::Base, which is accessed by your application via ApplicationController. Specifically, params refers to the parameters being passed to the controller via a GET or POST request.


1 Answers

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

params.permit(
  users_to_employers: [
    :start_date,
    :end_date,
    employer: [ :company_name ]
  ]
)
like image 52
Mike Szyndel Avatar answered Oct 03 '22 18:10

Mike Szyndel