I would like to override ActiveRecord's association methods in some instances (related to caching the foreign keys of indirect belongs_to
relationships. A typical example is a QuoteStop
has a Stop
and a Stop
has a PostalCode
and I want to cache the postal_code_id
at the QuoteStop
level also.
For this example, I'd like to add something like the following:
class QuoteStop
attr_accessible :stop_id, :postal_code_id
belongs_to :stop
belongs_to :postal_code
def postal_code_id
self[:postal_code_id] or postal_code_id!
end
def postal_code_id!
self.postal_code_id = stop.postal_code_id
end
def postal_code
self[:postal_code_id] ? super : PostalCode.find(postal_code_id) if postal_code_id
end
end
class Stop
attr_accessible :postal_code_id
end
The problem is that this seems to bypass the cache for postal_code
. For example, the following will result in n+1 queries where it should just result in 2.
QuoteStop.includes(:postal_code).limit(n).collect { |qs| qs.postal_code.name }
How do I use this technique without sacrificing the performance gains of ActiveRecord caching?