什麼是強引數

正如 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