2009/8/30 Tony <[email protected]>: > > So I'd like to set up the below associations. An Event is a normal AR > model. Stat is a normal AR model. I want a special stat on Event > that is a DB computation (mostly just sums of each column) and a > summary of all the Stats for that Event. The Summary isn't persisted > and is marked as readonly. Unfortunately, preloading is important in > this case (and thus why I went off on the group_by tangent, sorry if > that wasn't clear). > > I guess I could make a new model for Summary referencing the stats > table which uses a special select and always adds the group by clause, > however, that seemed like overkill. I really didn't want to run a > loop over the returned stats since the DB can give me exactly what I'm > looking for on the initial query. > > Ok, here's a slightly abridged version of what I thought might work: > > Event: > has_many :stats > has_one :summary_stat, :select => "sum(people) as > people, ...", :class_name => 'Stat', :foreign_key => > 'event_id', :readonly => true > > Stat: > belongs_to :event > > Adding "group" to the has_one solves the issue, but am I going about > this in the "right" way? Thanks for the input! > > tony >
I don't think I would go about it this way. Using Event has_one summary_stat suggests that somewhere there is a model SummaryStat that belongs_to event. An alternative would be to define an appropriate named scope in Stat that provides the summed stats using the single query and provide a read only attribute of Event that calls it and provides the answer. Colin --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---

