强参数:params.permit returns 尽管有白名单但不允许的参数

Strong Params: params.permit returns Unpermitted parameters despite whitelist

UsersProfileController 具有如下所示的强大参数:

    def user_profile_params
      params.permit(:age, :relations)
      # yes, I am not requiring user_profile. Just permitting attributes I need. 
    end

创建操作通过父级(has-one and belongs-to 关联)构建 UserProfile

    def create
      parent = Parent.create_guest
      parent.build_user_profile(user_profile_params)
      if parent.save 
        # do something 
      else 
        # handle error
      end
    end

调用 UserProfiles 中的参数 returns:

    <ActionController::Parameters 
      {"age"=>"23", 
       "relations"=>"3", 
       "subdomain"=>"api", 
       "format"=>:json, 
       "controller"=>"api/v1/user_profiles", 
       "action"=>"create"} 
     permitted: false>

正在调用 user_profile_params、returns 这个:

    user_profile_params:
      Unpermitted parameters: subdomain, format
      <ActionController::Parameters 
       {"age"=>"23", 
       "relations"=>"3", } 
      permitted: true>

当收到 post 请求时,我希望能够使用 user_profile_params 中的白名单参数创建 user_profile。相反,UserProfiles 中的 create 操作失败并出现错误:Unpermitted parameters: subdomain, format

这不是我所期望的。我希望 user_profile_params 只包含允许的值并忽略所有其他值。

我可以将 :format:subdomain 添加到允许的属性列表中,但感觉有点不对劲。

谁能解释一下是怎么回事 on/what 我失踪了?

此消息只是 警告,而不是 error/exception。如果您的模型没有被持久化,那是另一个原因。

来自strong parameters docs

Handling of Unpermitted Keys

By default parameter keys that are not explicitly permitted will be logged in the development and test environment. In other environments these parameters will simply be filtered out and ignored.

Additionally, this behaviour can be changed by changing the config.action_controller.action_on_unpermitted_parameters property in your environment files. If set to :log the unpermitted attributes will be logged, if set to :raise an exception will be raised.

你可以在你的控制台中模拟它(rails c):

fake_params_hash = {
    "age"=>"23", 
    "relations"=>"3", 
    "subdomain"=>"api", 
    "format"=>:json, 
    "controller"=>"api/v1/user_profiles", 
    "action"=>"create"
} 

permited_params = ActionController::Parameters.new(fake_params_hash).permit(:age, :relations)
#=> Unpermitted parameters: subdomain, format <== warning logged to the console
#=> <ActionController::Parameters {"age"=>"23", "relations"=>"3"} permitted: true>


user = User.create(permited_params) #mass assigment with permited params

#check if there are errors
puts user.errors.messages if user.errors.any?

如您所见,此消息不是由 User.create 抛出,而是在调用 .permit 时抛出。