Default Embedded Document

205 views
Skip to first unread message

Trevor Little

unread,
Feb 16, 2011, 12:21:50 PM2/16/11
to mon...@googlegroups.com
Hi,
   Is there a way to specify a default value for an embedded document or use hooks to mimic that behavior? For example, say I have these two classes:

class Foo
  include Mongoid::Document
  embeds_one :bar
end

class Bar
  include Mongoid::Document
  embedded_in :foo, :inverse_of => :bar
  field :count, :type => Integer, :default => 0
end

Now I want to be able to do this:

f = Foo.new
f.bar.count # should return 0

Is there anyway to do this? It seems like something I could implement with a before_<somethingorother> hook but I can't seem to get it to work.

I'm on Mongoid 2.0.0.beta.20, Rails 3.0.4 and Ruby 1.9.2

Thanks in advance for your help.

Trevor

Visnu Pitiyanuvath

unread,
Feb 16, 2011, 12:30:17 PM2/16/11
to mon...@googlegroups.com
maybe an after_initialize hook?

bundacia

unread,
Feb 16, 2011, 12:48:10 PM2/16/11
to Mongoid
So does that just get called on 'new' or does it get called on create
and find as well? I've had a hard time figuring out which hooks get
called when.

Trevor

bundacia

unread,
Feb 16, 2011, 1:41:52 PM2/16/11
to Mongoid
That seems to be working.

Thanks for the quick reply!

Trevor
Reply all
Reply to author
Forward
0 new messages