So, I know how to override the default recipients for attributes of an ActiveRecord object using
def custom_getter return self[:custom_getter] || some_default_value end
I try to achieve the same, but for the association belongs. For example.
class Foo < AR belongs_to :bar def bar return self[:bar] || Bar.last end end class Bar < AR has_one :foo end
When I speak:
f = Foo.last
I would like the f.bar method f.bar return the last line, not nil if this relationship does not already exist.
However, this does not work. The reason is that self [: bar] is always undefined. This is actually self [: bar_id].
I can do something naive like:
def bar if self[:bar_id] return Bar.find(self[:bar_id]) else return Bar.last end end
However, this will always cause a db call, even if Bar has already been checked out, which is certainly not ideal.
Does anyone have an idea of how I can relate, so the belongs_to attribute is only loaded once and has a default value if it is not set.
ruby-on-rails activerecord default-value associations
brad Mar 23 '10 at 14:44 2010-03-23 14:44
source share