-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
Goal: I try to provide a default Object for an embedded 1:1 relation that depends on data in other fields being available.
My way might look in a little odd, but it appeared to me as the most elegant solution I could find so far:
class Person include Mongoid::Document embeds_one :name def name_with_default name_without_default or (self.name = Name.new) end alias_method_chain :name, :default end
It worked until v3.0.9 and results in an infinite recursion loop since v3.0.10. This commit breaks it: https://github.com/mongoid/mongoid/commit/d07a1915c9f9d345652811ddaee6fb5b6b921132
Changed behaviour: the setter now always calls the getter first before setting what returns here now in an infinite recursion since the object.blank? is not used anymore.
Another solution to use write_attribute :name, ... does not work since it does not wrap Name.new in an proxy object for the association. The only other working solution for me is calling the internals directly and get around using the setter method:
(:name, Name.new.substitutable, Person.relations['name'])
Which seems a lot more odd to me.
Failing spec to show the issue: https://gist.github.com/4119739
Not sure what the best way really is to archive the goal. But I think it would be nice to have the old behaviour working again, since the same method works still for all other fields (afaik).