Created
August 18, 2011 07:23
-
-
Save conrad-vanl/1153583 to your computer and use it in GitHub Desktop.
Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person | |
include MongoMapper::Document | |
one :address, :as => :addressable | |
end | |
class Address | |
include MongoMapper::Document | |
belongs_to :addressable, :polymorphic => true | |
end | |
# Console: | |
irb(main):003:0> p = Person.create | |
=> #<Person _id: BSON::ObjectId('4e4cbcd7d70fd90e24000005')> | |
irb(main):004:0> a = Address.create | |
=> #<Address _id: BSON::ObjectId('4e4cbcdcd70fd90e24000007')> | |
irb(main):005:0> a.addressable = p | |
=> #<Person _id: BSON::ObjectId('4e4cbcd7d70fd90e24000005')> | |
irb(main):011:0> a.save | |
=> true | |
irb(main):006:0> p.address | |
=> nil | |
# If I reverse the assigning like so, then things kind of work, but still not properly: | |
irb(main):013:0> p = Person.create | |
=> #<Person _id: BSON::ObjectId('4e4cbd7ad70fd90e2400000f')> | |
irb(main):014:0> a = Address.create | |
=> #<Address _id: BSON::ObjectId('4e4cbd7dd70fd90e24000011'), addressable_id: nil, addressable_type: nil> | |
irb(main):015:0> p.address = a | |
=> #<Address _id: BSON::ObjectId('4e4cbd7dd70fd90e24000011'), addressable_id: nil, addressable_type: nil, person_id: BSON::ObjectId('4e4cbd7ad70fd90e2400000f')> | |
irb(main):016:0> p.save | |
=> true | |
irb(main):017:0> a.save | |
=> true | |
irb(main):018:0> a | |
=> #<Address _id: BSON::ObjectId('4e4cbd7dd70fd90e24000011'), addressable_id: nil, addressable_type: nil, person_id: BSON::ObjectId('4e4cbd7ad70fd90e2400000f')> | |
irb(main):019:0> p | |
=> #<Person _id: BSON::ObjectId('4e4cbd7ad70fd90e2400000f')> | |
# Notice how it is assigning a "person_id" key to the address object, and leaving the addressable_* keys nil. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment