Spec-Zone.ru › Ruby on Rails 7.2

модуль ActionController::StrongParameters

Сильные 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.require(:person).permit(: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.require(:person).permit(:name, :age, pets_attributes: [ :id, :name, :category ])
    end
end

См. ActionController::Parameters.require и ActionController::Parameters.permit для получения дополнительной информации.

Публичные методы экземпляра

params() Показать исходный код
# File actionpack/lib/action_controller/metal/strong_parameters.rb, line 1326
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

Возвращает новый ActionController::Parameters объект, который был инициализирован с request.parameters.

params=(value) Показать исходный код
# File actionpack/lib/action_controller/metal/strong_parameters.rb, line 1341
def params=(value)
  @_params = value.is_a?(Hash) ? Parameters.new(value) : value
end

Присваивает указанный value в хеш params. Если value является Hash, это создаст ActionController::Parameters объект, который был инициализирован с данным хешем value.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API