mongoid/mongoid — Issue #1398: Fields Defaults with Proc conditional throwing errors
Author: fullbridge-batkins
Created: 2011-11-01 22:30:36+00:00
State: open

Using Mongoid 2.2.4

I have an embedded document like this, and I was trying to use a conditional on the default value for one of my fields, but ran into some issues. I tried following the directions on http://mongoid.org/docs/documents/fields.html, and even looked at one of the mongoid issues related to this at (https://github.com/mongoid/mongoid/issues/1075), but still couldn't figure out how to get it to work.

class Role
include Mongoid::Document

embedded_in :user, :inverse_of => :roles
field :code
field :program_calendar, :default => lambda { |role| role.code == "code_a" ? "special_value" : "default_value" }

end

But every time I tried to use it in the console, I kept getting an error: NoMethodError: undefined method `code' for nil:NilClass

My eventual solution was to create a method and call it using 'before_save' to set the default value at that point, but I would prefer to use the lambda conditional if this is possible? What am I doing wrong? Do I need a newer version of Mongoid?