将mysql查询移动到模型

时间:2012-11-03 18:29:58

标签: mysql ruby-on-rails ruby-on-rails-3

我有以下mysql查询运行良好。快速背景故事,这列出了我们的客户花费的总金额。

SELECT  SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
FROM customer_order AS co 
JOIN customer AS cu ON (cu.customer_id = co.customer_id) 
GROUP BY co.customer_id
ORDER BY money_spent DESC

我尝试将其转移到客户模型,作为范围和子类,但我两种方式都失败了。我对rails(以前的客户端)有些新意,但我认为我很接近。希望你们都能指出我正确的方向。在此先感谢!!!

def self.high_rollers  
  options = {
      :select   => "SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary",
      :from     => "customer_order AS co",
      :joins    => "customer AS cu ON (cu.customer_id = co.customer_id)",
      :group_by => "co.customer_id",
      :order    => "money_spent DESC"
            }   

将以下代码放在我的这个控制器的索引操作中可以正常工作,但绝对不是正确的方法!

@high_bidders = Customer.find_by_sql(<<-SQL
       SELECT  SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
       FROM customer_order AS co 
       JOIN customer AS cu ON (cu.customer_id = co.customer_id) 
       GROUP BY co.customer_id
       ORDER BY money_spent DESC

SQL  )

1 个答案:

答案 0 :(得分:1)

我假设您的模型名称是Customer和CustomerOrder。您的表名称不是常规的,我认为您已经在使用self.table_name的模型中明确设置了表名。

class CustomerOrder < ActiveRecord::Base
  # ...
  belongs_to :customer

  scope :high_rollers, select("*, SUM(price) AS money_spent").
                       joins(:customer).
                       group(:customer_id).
                       order("money_spent DESC")
end