Ruby on Rails latest stable (v4.0.2) - 0 notes
  • 1.0.0
  • 1.1.1
  • 1.1.6
  • 1.2.0
  • 1.2.6
  • 2.0.0
  • 2.0.3
  • 2.1.0
  • 2.2.1
  • 2.3.2
  • 2.3.8
  • 3.0.0
  • 3.0.5
  • 3.0.9
  • 3.1.0
  • 3.2.1
  • 3.2.3
  • 3.2.8
  • 3.2.13
  • 4.0.2 (0)
  • What's this?

Strong Parameters

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 whitelisted.

In addition, parameters can be marked as required and flow through a predefined raise/rescue flow to end up as a 400 Bad Request with no effort.

class PeopleController < ActionController::Base
  # Using "Person.create(params[:person])" would raise an
  # ActiveModel::ForbiddenAttributes exception because it'd
  # be using mass assignment without an explicit permit step.
  # This is the recommended form:
  def create

  # This will pass with flying colors as long as there's a person key in the
  # parameters, otherwise it'll raise an ActionController::MissingParameter
  # exception, which will get caught by ActionController::Base and turned
  # into a 400 Bad Request reply.
  def update
    redirect_to current_account.people.find(params[:id]).tap { |person|

    # Using a private method to encapsulate the permissible parameters is
    # just 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.
    def person_params
      params.require(:person).permit(:name, :age)

In order to use accepts_nested_attribute_for with Strong Parameters, you will need to specify which nested attributes should be whitelisted.

class Person
  has_many :pets
  accepts_nested_attributes_for :pets

class PeopleController < ActionController::Base
  def create



    def person_params
      # It's mandatory to specify the nested attributes that should be whitelisted.
      # If you use `permit` with just the key that points to the nested attributes hash,
      # it will return an empty hash.
      params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])

See ActionController::Parameters.require and ActionController::Parameters.permit for more information.

Show files where this module is defined (1 file)
Register or log in to add new notes.