简体   繁体   中英

Ruby on Rails, find top 5 Users ordered by purchases

I have 2 models, User and Purchase. A User has_many :purchases and a Purchase belongs_to :user

Purchases fields are:

id, product_id, user_id, amount, created_at

What I am trying to achieve is a method call such as: User.top_five which would return the 5 Users with the highest purchase value, ie the sum of the purchases.amount field for each user.

I also want to be able to do something like User.top_five(:start_date=>'01/01/2010',:end_date=>'31/12/2010') , ie select a time period to calculate the top five users.

So I've been trying to get the right combination of joins, sums, order_bys etc, but I'm just not getting it. So hopefully someone can point me in the right direction! Hopefully I've given enough info here, this is my first question.

thanks

I suggest something like

def self.top_five(start_date, end_date)
  User.all(:select => "users.*, SUM(purchased.amount) as purchased_sum",
           :joins => "LEFT JOIN purchases AS purchased ON purchased.user_id = users.id",
           :group => "users.id",
           :conditions => ["purchased.created_at BETWEEN ? AND ?", start_date, end_date],
           :order => "purchased_sum DESC",
           :limit => 5)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM