Question

Consider this example:

> x = User.first # or any persisted Mongoid::Document
=> #<User _id: 52014532a6356d1ac9000001, ...>
> x.set :foo, :bar
=> :bar
> x.set :foo2, 'bar'
=> "bar"

Note that "foo" and "foo2" are not declared in Ruby anywhere.

THEN, in a MongoDB shell:

> db.users.findOne({_id: ObjectId('52014532a6356d1ac9000001')})    
{
  "_id" : ObjectId("52014532a6356d1ac9000001"),
  "foo" : "bar",
  "foo2" : "bar",
  ...
}

BUT NOW, back in Ruby:

> x = User.find x.id; nil # to clear out any possibility of metadata on the instance
=> nil
> [x.read_attribute(:foo), x.read_attribute(:foo2)]
=> [:bar, "bar"]

How does it know?

Was it helpful?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top