什么是强参数

正如 edgeapi 所建议的那样,它提供了一个保护属性免受最终用户分配的界面。这使得动作控制器参数被禁止在活动模型批量分配中使用,直到它们被列入白名单。

此外,参数可以根据需要进行标记,并通过预定义的加油/救援流程最终作为 400 Bad Request 而不费力。请查看 PeopleController 文件和列出的注释,以了解如何使用强参数?

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::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|
      person.update!(person_params)
    }
  end

  private
    # 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)
    end
end