如何从 Mongoid 模型中删除属性,即不仅仅是取消它们的值
我正在尝试 Mongoid 中的多态关联,
class Group
include Mongoid::Document
belongs_to :groupable, polymorphic: true
end
class Album
include Mongoid::Document
has_many :groups, as: groupable
end
然后我决定不这样做。所以我删除了上面所有的belongs_to和has_many行。然而在控制台中,每当我获得我尝试过的组记录时,它仍然具有此“groupable_type”属性。我知道remove_attribute会使属性无效,但不会删除它(听起来有点像JavaScript)。我怎样才能真正从 Mongoid 的数据库中删除这个属性?
I was experimenting the polymorphic associaton in Mongoid
class Group
include Mongoid::Document
belongs_to :groupable, polymorphic: true
end
class Album
include Mongoid::Document
has_many :groups, as: groupable
end
then I decided against it. So I removed all those belongs_to and has_many lines above. Yet in the console, whenever I get a Group record that I experimented with, it still has this "groupable_type" attribute. I know remove_attribute nullify the attribute, but does not remove it( sounds a bit like JavaScript). How can I actually remove this attribute from the database from Mongoid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样做:
You could do this:
从 Mongoid 5.0.0 版本开始,gem 已从使用 Moped 切换为使用“官方 ruby MongoDB 驱动程序”,该驱动程序具有不同的更新语法。参考:https://docs.mongodb.org/ecosystem/drivers/ruby/
收集方法的文档在这里:
http://api.mongodb.org/ruby/current/Mongo/Collection.html
有两种方法,“update”和“update_many”。您可以使用 update_many 而不是指定 'multi' 选项来更新所有文档。
OP 案例的使用示例:
请注意,您可以使用点表示法取消设置嵌入文档:
请注意,MongoDB 不太支持取消设置/更新数组中的字段。有关信息和解决方法,请参阅此线程: https://jira.mongodb.org/browse/SERVER-1243 。
As of version 5.0.0 of Mongoid, the gem has switched from using Moped to use the 'official ruby MongoDB driver' which has a different syntax for updates. Reference: https://docs.mongodb.org/ecosystem/drivers/ruby/
The documentation for collection methods is here:
http://api.mongodb.org/ruby/current/Mongo/Collection.html
There are 2 methods, "update" and "update_many". You can use update_many instead of specifying the 'multi' option to update all documents.
Example use for the OPs case:
Note you can unset embedded documents using dot notation:
Note it is not well supported by MongoDB to unset / update fields within an array. See this thread for info and workarounds: https://jira.mongodb.org/browse/SERVER-1243.
对于单个实例,可以(至少在 Mongoid 的最新版本中)直接在实例上使用
unset
For a single instance, it is possible (at least in recent versions of Mongoid) to use directly
unset
on your instance我注意到 Moped 2.0.0.rc1 中的更新方法在集合中消失了,但这有效;
I noticed in Moped 2.0.0.rc1 the update method is gone on collection, but this works;