简体   繁体   English

您可以在Rails操作中从post_params中删除吗?

[英]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.

相关问题 保存前如何从post_params获取和使用对象的ID - How can I get and use the id of an object from post_params before saving 正如您可以将参数从一个动作传递到另一个动作一样? - As you can pass params from one action to another? 借助rails before_action,您如何防止恶意用户创建,更新,编辑和删除 - With rails before_action how can you protect from malicious users for create / update / edit and delete 使用Rails Action View帮助器时,如何自定义参数使其成为标签数组? - When using rails Action View Helpers - how can you customize the params to be an Array of the labels? PostsController中的NameError#为#创建未定义的局部变量或方法`post_params&#39; <PostsController:0x007fd289176ae8> - NameError in PostsController#create undefined local variable or method `post_params' for #<PostsController:0x007fd289176ae8> 如何在Rails测试中指定POST参数? - How do you specify POST params in a Rails test? 参数值仅在您调用它的操作中可用吗? (路轨) - Are params values only available in the action you call it in? (Rails) 在Rails中,如何从视图中输出动作的名称? - In Rails, how can you output the name of the action from inside the view? 无法访问从React客户端发送到POST请求中的params到Rails api - Can't access params sent in POST request from React client to Rails api Rails发布日期参数 - Rails Post Date Params
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM