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.
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.
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.
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.
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.
To accept an array of objects, put the params in an array:
params.permit(
users_to_employers: [
:start_date,
:end_date,
employer: [ :company_name ]
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With