如何将SQL查询编写为named_scope?

时间:2010-05-01 11:10:52

标签: sql ruby-on-rails

如何将以下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

谢谢!

1 个答案:

答案 0 :(得分: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