2010-05-01 77 views
0

如何將以下SQL查詢轉換爲named_scope?如何將SQL查詢編寫爲named_scope?

select users.*, sum(total_quantity * total_price) as points_spent 
from orders 
join users on users.id = orders.user_id 
where pay_type = 'points' 
group by user_id 
order by points_spent desc 

謝謝!

回答

4

嘗試這個

class User < ActiveRecord::Base 

    named_scope :your_name, 
       :select=>" users.*,sum(total_quantity * total_price) as points_spent",  
       :joins => :orders, 
       :conditions => ['pay_type = ?', 'points'], 
       :group ="user_id ", 
       :order=>'points_spent desc' 

end