Reputation: 43402
I have an ActiveRecord Model (I'll refer to as owner) that is effectively a container for another type of Model (I'll refer to as posession) stored in a has_many
through association. Effectively almost all of its attributes are based on accumulated data from its many posessions.
For example it needs a start and end year which will be based on the earliest and latest years of its posessions. It also needs to have a tags association that is made up of all the tags from all of its posessions. So effectively all owner is, is an enumeration of the data from all of its posessions.
How should I handle this? I need owners to be searchable with *pg_search* so I can't simply use virtual attributes as accessors to enumerate the attributes of the posessions, and that would be very expensive.
Should I look at having owner re-calculate its attributes whenever a posession is saved so that they are only recalculated once per change rather than every time they are needed?
I'm at a loss how to handle this so any suggestions would be appreciated.
Upvotes: 0
Views: 94
Reputation: 3475
Have you looked at using SQL joins? Something like:
@owners = Owner.find(
:all,
:select => 'owners.*, sum(possessions.amount) as total_amount',
:joins => 'left outer join possessions on possessions.owner_id = owners.id',
:conditions => { 'owners.active => false },
:group => 'owners.id',
:order => 'owners.name'
)
This gives you an ActiveRecord relation with the extra attributes you define in the select call, so in this instance you could access the sum as an normal attribute, e.g.
@owners.first.total_amount
Not quite sure how pg_search works, but seems like it'd be compatible w/ a SQL join?
Edit: Whoops, that initial find should be on Owner, not Possession.
Upvotes: 1