Created
October 13, 2012 05:36
-
-
Save pqwy/3883367 to your computer and use it in GitHub Desktop.
can't re-add live objects back into a relation
This file contains 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 A | |
include Mongoid::Document | |
has_many :bs | |
end | |
class B | |
include Mongoid::Document | |
belongs_to :a | |
end | |
# populate | |
a = A.create | |
the_bs = [B.create, B.create] | |
a.bs << the_bs | |
a.save | |
# what do we have? | |
a.bs.count | |
# => 2 | |
# now reset the relation | |
a.bs.nullify | |
# and now? | |
a.bs | |
# => [] | |
a.bs.count | |
# => 0 | |
# ok, let's add _something_ | |
a.bs << the_bs[0] | |
# => [#<B _id: 5078fc1e5f2869aa4e000007, _type: nil, a_id: "5078fc1d5f2869aa4e000006">] | |
# Right! But... | |
a.bs.count | |
# => 0 | |
# uh-oh.... | |
a.bs.map(&:a_id) | |
# => ["5078fc1d5f2869aa4e000006"] | |
a.bs.map(&:persisted?) | |
=> [true] | |
## at this point, the "B" object has its :a_id set to nil in the database, but mongoid | |
# believes it's already persisted and refuses to write it, ever. the array and the state | |
# in the database have diverged, and the database will never pick it up. | |
a.bs.each(&:save!) | |
# => true | |
a.bs.count | |
# => 0 | |
# the same can be achieved by assigning "A" directly | |
the_bs[1].a | |
# => nil | |
the_bs[1].a = a | |
# => #<A _id: 5078fc1d5f2869aa4e000006, _type: nil> | |
the_bs[1].persisted? | |
# => true | |
the_bs[1].save! | |
# => true | |
the_bs[1].a | |
# => #<A _id: 5078fc1d5f2869aa4e000006, _type: nil> | |
the_bs[1].reload | |
the_bs[1].a | |
# => nil | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment