Here's my current named_scope. It returns an aggregate result from a number of rows. Sample result from 300 rows:
- Total Points: 3000
- Wins: 31
- Losses: 11
Here is the code:
named_scope :open_for, lambda { |sportable_id, sportable_type, days_ago| { :conditions => ['sportable_id = ? and sportable_type = ? and game_time > ? ', sportable_id, sportable_type, days_ago] } } do
def total
self.sum('open_for')
end
def wins
self.count(:conditions => ['open_for > ?', 0])
end
def losses
self.count(:conditions => ['open_for < ?', 0])
end
end
The problem with this named_scope is that everything I run .total, .wins, .losses, it re-queries the DB, making it very inefficient. Is there a way I can return total, wins, and losses in a single query? It doesn't have to be a named_scope. It can be find_by_sql.