StrongParameters¶↑
It provides an interface for protecting attributes from end-user assignment. This makes Action Controller parameters forbidden to be used in Active Model mass assignment until they have been explicitly enumerated.
In addition, parameters can be marked as required and flow through a predefined raise/rescue flow to end up as a400 Bad Request with no effort.
classPeopleController<ActionController::Base# Using "Person.create(params[:person])" would raise an# ActiveModel::ForbiddenAttributesError exception because it'd# be using mass assignment without an explicit permit step.# This is the recommended form:defcreatePerson.create(person_params)end# This will pass with flying colors as long as there's a person key in the# parameters, otherwise it'll raise an ActionController::ParameterMissing# exception, which will get caught by ActionController::Base and turned# into a 400 Bad Request reply.defupdateredirect_tocurrent_account.people.find(params[:id]).tap {|person|person.update!(person_params) }endprivate# Using a private method to encapsulate the permissible parameters is# a good pattern since you'll be able to reuse the same permit# list between create and update. Also, you can specialize this method# with per-user checking of permissible attributes.defperson_paramsparams.expect(person: [:name,:age])endend
In order to useaccepts_nested_attributes_for with StrongParameters, you will need to specify which nested attributes should be permitted. You might want to allow:id and:_destroy, seeActiveRecord::NestedAttributes for more information.
classPersonhas_many:petsaccepts_nested_attributes_for:petsendclassPeopleController<ActionController::BasedefcreatePerson.create(person_params)end...privatedefperson_params# It's mandatory to specify the nested attributes that should be permitted.# If you use `permit` with just the key that points to the nested attributes hash,# it will return an empty hash.params.expect(person: [:name,:age,pets_attributes: [:id,:name,:category ] ])endend
SeeActionController::Parameters.expect, SeeActionController::Parameters.require, andActionController::Parameters.permit for more information.
Instance Public methods
params()Link
Returns a newActionController::Parameters object that has been instantiated with therequest.parameters.
params=(value)Link
Assigns the givenvalue to theparams hash. Ifvalue is aHash, this will create anActionController::Parameters object that has been instantiated with the givenvalue hash.