Uzz*_*zar 5 ruby parameters ruby-on-rails strong-parameters ruby-on-rails-5
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和belongs-to association)构建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中调用params返回:
    <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.相反,createUserProfiles中的操作失败,错误:Unpermitted parameters: subdomain, format.
这不是我的预期.我希望user_profile_params只包含允许的值并忽略所有其他值.
我可以添加:format和:subdomain列出允许的属性,但有些东西感觉有点不对劲.
有人可以解释发生了什么/我错过了什么?
此消息只是警告,而不是错误/异常。如果你的模型没有被持久化,那是由另一个原因造成的。
来自强参数文档:
处理未经许可的密钥
默认情况下,未明确允许的参数键将记录在开发和测试环境中。在其他环境中,这些参数将被简单地过滤掉并忽略。
此外,可以通过更改环境文件中的 config.action_controller.action_on_unpermissed_parameters 属性来更改此行为。如果设置为 :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调用时抛出的。
| 归档时间: | 
 | 
| 查看次数: | 2682 次 | 
| 最近记录: |