跳至内容 跳至搜索

Parameters

它提供了一个接口来保护属性免受最终用户分配。这使得 Action Controller 参数在明确枚举之前,不能用于 Active Model 批量赋值。

此外,参数可以标记为必需,并通过预定义的 raise/rescue 流程,最终以 400 Bad Request 结束,无需任何努力。

class PeopleController < 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:
  def create
    Person.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.
  def update
    redirect_to current_account.people.find(params[:id]).tap { |person|
      person.update!(person_params)
    }
  end

  private
    # 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.
    def person_params
      params.expect(person: [:name, :age])
    end
end

为了使用 accepts_nested_attributes_for 与强 Parameters 一起使用,你需要指定哪些嵌套属性应该被允许。你可能希望允许 :id:_destroy,有关更多信息,请参阅 ActiveRecord::NestedAttributes

class Person
  has_many :pets
  accepts_nested_attributes_for :pets
end

class PeopleController < ActionController::Base
  def create
    Person.create(person_params)
  end

  ...

  private

    def person_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 ] ])
    end
end

有关更多信息,请参阅 ActionController::Parameters.expect,参阅 ActionController::Parameters.requireActionController::Parameters.permit

方法
P

实例公共方法

params()

返回一个新的 ActionController::Parameters 对象,该对象已使用 request.parameters 实例化。

# File actionpack/lib/action_controller/metal/strong_parameters.rb, line 1514
def params
  @_params ||= begin
    context = {
      controller: self.class.name,
      action: action_name,
      request: request,
      params: request.filtered_parameters
    }
    Parameters.new(request.parameters, context)
  end
end

params=(value)

将给定的 value 分配给 params 哈希。如果 value 是一个 Hash,这将创建一个 ActionController::Parameters 对象,该对象已使用给定的 value 哈希实例化。

# File actionpack/lib/action_controller/metal/strong_parameters.rb, line 1529
def params=(value)
  @_params = value.is_a?(Hash) ? Parameters.new(value) : value
end