Skip to content

Instantly share code, notes, and snippets.

@MyounghoonKim
Last active December 28, 2015 04:39
Show Gist options
  • Save MyounghoonKim/7444281 to your computer and use it in GitHub Desktop.
Save MyounghoonKim/7444281 to your computer and use it in GitHub Desktop.
CRUD action on embedded document on MongoMapper
# User embeds Other and Other embeds Shops.
require 'mongo_mapper'
class User
include MongoMapper::Document
key :email, String, :required => true
one :other
end
class Other
include MongoMapper::EmbeddedDocument
many :shops
end
class Shop
include MongoMapper::EmbeddedDocument
key :name, String, :required => true
key :id, String, :requried => true
key :pw, String, :requried => true
end
User.create(
:email => "[email protected]",
:other => {
:shops => [
{
:name => "totoro",
:id => "asdfsdf",
:pw => "pw"
},
{
:name => "iphone",
:id => "asdf",
:pw => "asdfsadf"
}
]
}
)
result = User.where('other.shops.name' => "totoro")
puts JSON.pretty_generate(JSON.parse(result.to_json))
User.set(
{ 'other.shops.name' => "totoro" },
'other.shops.$.pw' => "changed"
)
result = User.where('other.shops.name' => "totoro")
puts JSON.pretty_generate(JSON.parse(result.to_json))
User.destroy_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment