简体   繁体   中英

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.

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. This is the reason why tags is still there as it wasn't deleted from the actual hash ie params in the first place.

You should be deleting the tags key from the actual hash ie params and not from the hash returned from post_params method call.

For example:

If params = {"post" => {"headline"=>"blah", "tags"=>"foo bar"}}

then use params["post"].delete("tags")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM