[英]Can you delete from post_params in a Rails action?
I'm trying to delete from the post_params
hash in my Rails update
action, but my delete
call seems like it's being ignored. 我正在尝试从Rails
update
操作中的post_params
哈希中delete
,但是delete
调用似乎被忽略了。
puts "before: #{post_params.inspect}"
# output: before {"headline"=>"blah", "tags"=>"foo bar"}
puts "deleted: #{post_params.delete("tags")}"
# output: deleted: foo bar
puts "after: #{post_params.inspect}"
# output: before {"headline"=>"blah", "tags"=>"foo bar"}
# WHY IS "tags" STILL THERE?
Am I making some kind of elementary noob mistake? 我在犯某种基本的菜鸟错误吗? This is driving me crazy because it seems so stupid.
这让我发疯,因为它看起来是如此愚蠢。
I am quite sure that post_params
is a method in your controller where you whitelist the attributes of your model and this method returns a new hash instance every time you call it. 我非常确定
post_params
是控制器中的一种方法,在该方法中您将模型的属性列入白名单,并且每次调用该方法都会返回一个新的哈希实例。 This is the reason why tags
is still there as it wasn't deleted from the actual hash ie params
in the first place. 这就是为什么
tags
仍然存在的原因,因为它并未从实际哈希(即params
中删除。
You should be deleting the tags
key from the actual hash ie params
and not from the hash returned from post_params
method call. 您应该从实际哈希(即
params
删除tags
键,而不是从post_params
方法调用返回的哈希中删除。
For example: 例如:
If params = {"post" => {"headline"=>"blah", "tags"=>"foo bar"}}
如果
params = {"post" => {"headline"=>"blah", "tags"=>"foo bar"}}
then use params["post"].delete("tags")
然后使用
params["post"].delete("tags")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.