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 errorsputs user.errors.messages if user.errors.any?
如您所见,User.create不会抛出此消息,但是在调用.permit时.
总结以上是内存溢出为你收集整理的ruby-on-rails – 强参数:params.permit返回未经许可的参数,尽管白名单全部内容,希望文章能够帮你解决ruby-on-rails – 强参数:params.permit返回未经许可的参数,尽管白名单所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)