【问题标题】:Strong Params: params.permit returns Unpermitted parameters despite whitelist强参数:params.permit 返回未经许可的参数,尽管有白名单
【发布时间】:2017-01-21 00:29:48
【问题描述】:

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

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

create 操作通过父级(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 中调用参数返回:

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

调用 user_profile_params,返回:

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

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

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

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

有人可以解释发生了什么/我错过了什么吗?

【问题讨论】:

  • 在我看来,您实际上并没有通过 UsersProfileController 中的创建块。
  • @ChrisMoody:不知道我明白你的意思。如果您的意思是该方法没有被调用,那么这是不正确的。能够进入 UsersProfileController 中的 create 操作,并发现在此特定行 parent.build_user_profile(user_profile_params) 上调用 user_profile_params 时发生错误。你能解释一下你的意思吗?

标签: ruby-on-rails ruby parameters ruby-on-rails-5 strong-parameters


【解决方案1】:

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

来自strong parameters docs

未经许可的密钥的处理

默认情况下,未明确允许的参数键将是 登录开发和测试环境。在其他环境 这些参数将被过滤掉并忽略。

此外,此行为可以通过更改 config.action_controller.action_on_unpermitted_pa​​rameters 属性 你的环境文件。如果设置为 :log 未经许可的属性将 被记录,如果设置为 :raise 将引发异常。

您可以在控制台中模拟它 (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 时抛出的。

【讨论】:

  • 你是对的。实际上是来发布错误是由于对User模型的验证。感谢您抽出宝贵的时间回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多