Skip to content

Instantly share code, notes, and snippets.

@ise
Last active August 16, 2018 12:53
Show Gist options
  • Save ise/861b98586d597f94f182e9f766d56036 to your computer and use it in GitHub Desktop.
Save ise/861b98586d597f94f182e9f766d56036 to your computer and use it in GitHub Desktop.
mongoid embeds_many
class A
include Mongoid::Document
embeds_many :items
end
class Item
include Mongoid::Document
embedded_in :a
field :text, type: String
end
a = A.new(items: [])
a.save
# > db.as.find({_id:ObjectId("5b75482054ffa1008b98cca2")})
# {
# "_id" : ObjectId("5b75482054ffa1008b98cca2")
# }
a.items = [Item.new(text: 'unko')]
# > db.as.find({_id:ObjectId("5b75482054ffa1008b98cca2")})
# {
# "_id" : ObjectId("5b75482054ffa1008b98cca2"),
# "items" : [
# {
# "_id" : ObjectId("5b75483554ffa1008b98cca3"),
# "text" : "unko"
# }
# ]
# }
a.items = []
# > db.as.find({_id:ObjectId("5b75482054ffa1008b98cca2")})
# {
# "_id" : ObjectId("5b75482054ffa1008b98cca2"),
# "items" : []
# }
@ise
Copy link
Author

ise commented Aug 16, 2018

Model#{name}=
Set the embedded documents. If the parent document is persisted, then the child will be atomically saved immediately. If setting to nil or [] then the children will be deleted.
https://mongoid.github.io/old/en/mongoid/docs/relations.html#embeds_many

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment