跳到內容 跳到搜尋

參數

這個模組提供一個介面用來防堵屬性遭到「 end user 」指定。這使得「 Action Controller 」參數遭到禁止,並用於「 Active Model 」大量指定,直到參數被明確列舉出來。

此外,參數可以標記為「需要」並且流經預先定義的「回應/救援」流程,終結為 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 加上「強參數」,您需要明確指定要允許的嵌套屬性。您可能會想要允許 :id:_destroy,有關更多的資訊,請參見 ActiveRecord:嵌套屬性

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:參數。期待,請參見 ActionController:參數。需要,以及 ActionController:參數。允許 以取得更多資訊。

方法
P

實體公有方法

params()

以已使用 request.parameters 進行例示化的方式,回傳新的 ActionController:參數 物件。

# 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 哈希值。如果 valueHash,這會建立一個 ActionController:參數 物件,這個物件已經使用提供的 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