references_one problem / bug

23 views
Skip to first unread message

Dirk Dressel

unread,
Aug 24, 2010, 1:29:47 PM8/24/10
to Mongoid
Lets take the "shortenend" example from http://mongoid.org/docs/associations/

class Person
include Mongoid::Document
references_one :policy
end

class Policy
include Mongoid::Document
field :policy, :type => Integer, :default => 1
referenced_in :person
end

racksh/console
person = Person.create
policy = Policy.create
person.policy = policy

Everything works fine here.
The policy gets referenced via person_id.

But in mongodb I get:

person_id: null
policy : null

The person_id and the default value are not persisted to mongodb!
the oid for policy is there.

If I change everything to references_many it works fine but not with
references_one

Using:
ruby1.9.2 newest
mongoid 2.0.0.beta16
mongodb1.6

Gagan Shrestha

unread,
Aug 25, 2010, 9:18:52 PM8/25/10
to mon...@googlegroups.com
I think you should call
person.save after assigning person.policy = policy because all those referencing only stays in memory not in database until you call save on person.

hope this might work.
--
with Regards
Gagan Shrestha
Web developer
Sprout Tech Pvt Ltd
Lalitpur, Nepal
+977 1 559-2701

Nicholas Young

unread,
Aug 25, 2010, 9:50:37 PM8/25/10
to mon...@googlegroups.com
Couldn't you call it like:

p = Person.create
p.policy.create

That might make it a bit more streamlined, but then again, I'm not 100% sure that syntax would work. Just an idea. 

Nicholas

Sent from my iPhone

Dirk Dressel

unread,
Aug 25, 2010, 11:22:51 PM8/25/10
to Mongoid
person = Person.create
policy = Policy.create
person.policy = policy

person.policy.save

saving person.policy is the solution!

Thanks a lot guys.


@Nicholas Young
p.policy.create
doesn´t work => undefined method `create' for nil:NilClass


One more problem.

Creating more than one policy leads to several documents with the same
person_id
Shouldn´t mongoid take care of this, since references_one is declared?

Shouldn´t mongoid only save one policy or on a second save just update
fields with different data?


Reply all
Reply to author
Forward
0 new messages