Rails 4 fake ActiveRecord property based on association

445 Views Asked by At

How do I fake a method in a ActiveRecord object to behave like a property if it depends on its associations?

To illustrate, let's say Update belongs_to Item. When I call Item.purchased_at, I want it to find the Update with kind: "purchased" and tell me when it was created:

# item.rb

def purchased_at
  self.updates.find_by_kind("purchased").try(:created_at)
end

def purchased_at=(time)
  u = self.updates.find_by_kind("purchased") || self.updates.new(kind: "purchased")
  u.mark_for_destruction unless u.time = time # queue for destruction if time is nil
end

My getter method, however, only returns what was already committed. It doesn't show the non-saved values like real ActiveRecord properties do:

item = Item.first
item.purchased_at = Time.now
item.save
item.purchased_at = nil
item.purchased_at # returns the current time

How should I change my code so purchased_at behaves like a real ActiveRecord property?

0

There are 0 best solutions below