简体   繁体   English

Ruby On Rails-从模型中删除属性

[英]Ruby On Rails - Remove attribute from model

I'm trying to remove an attribute from params before to update an object, but i don't succeed to do it. 我试图在更新对象之前从params中删除一个属性,但是我没有成功做到这一点。

Params contain an object Post, and i want to remove image_url from it : 参数包含一个对象Post,我想从其中删除image_url:

{
 "post" : "{
     \"content\" : \"dfsgdfa\",
     \"created_at\" : \"2013-09-01T08:39:26Z\",
     \"id\" : 21,
     \"image_content_type\" : \"image/jpeg\",
     \"image_file_name\" : \"img.jpg\",
     \"image_file_size\" : 61140,
     \"image_updated_at\" : \"2013-09-01T08:39:26Z\",
     \"title\" : \"sdsdsdd\",
     \"updated_at\" : \"2013-09-01T08:39:26Z\",
     \"user_id\" : 4,
     \"image_url\" : \"/system/posts/images/000/000/021/original/img.jpg?137802476
  \"}",
  "image" : "null",
  "action" : "update",
  "controller" : "posts",
  "id" : "21"
}

So i did like that : 所以我确实那样:

params[:post].delete("image_url")

No errors are raised, but image_url is still in params[:post] 没有引发任何错误,但是image_url仍然在params [:post]中

How can i delete it ? 我如何删除它?

params[:post] is actually string in your case. 在您的情况下, params[:post]实际上是字符串。 It's not a hash. 这不是哈希。 That's why it is not working. 这就是为什么它不起作用。

params[:post] is not a hash, when you inspect it over controller it will look like hash. params [:post]不是哈希,当您通过控制器检查它时,它将看起来像哈希。 It's actually ActiveSupport::HashWithIndifferentAccess instance. 它实际上是ActiveSupport :: HashWithIndifferentAccess实例。

You can not remove a key/value pair from a Hash using Hash#delete: you should to write before save callback 您不能使用Hash#delete从哈希中删除键/值对:您应该在保存回调之前编写

def delete_image_url
  params[:post].delete :image_url
end

I hope it will help you. 希望对您有帮助。 I already tested it. 我已经测试过了

You can pass a subset into whatever function you want with: 您可以将子集传递给所需的任何函数:

@object = Foo.new(params.reject{|key,value| key == 'image_url'})

This doesn't remove it entirely from params, but returns a copy without that key 这不会将其完全从params中删除,但是会返回没有该键的副本

params ['post']。delete(“ image_url”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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