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?
You could do this:
Group.collection.update({},
{'$unset' => {:groupable_type => 1}},
:multi => true)
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:
Group.collection.update_many({}, {'$unset' => {'groupable_type' => true}})
Note you can unset embedded documents using dot notation:
Group.collection.update_many({}, {'$unset' => {'embedded_doc.groupable_type' => true}})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With