当前位置: 动力学知识库 > 问答 > 编程问答 >

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 i.e. params in the first place.

You should be deleting the tags key from the actual hash i.e. 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")

分享给朋友:
您可能感兴趣的文章:
随机阅读: