加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 强参数:params.permit返回未经许可的参数,尽

发布时间:2020-12-17 03:10:39 所属栏目:百科 来源:网络整理
导读: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)构建UserP
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",} 
      permitted: true>

当发布请求时,我希望能够使用user_profile_params中的白名单参数创建user_profile.相反,UserProfiles中的创建操作失败并显示错误:未允许的参数:子域,格式.

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

我可以添加:format和:subdomain到允许的属性列表,但有些东西感觉有点不对劲.

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

解决方法

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

从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","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时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读