2

我有以下 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)

4

1 回答 1

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
于 2012-11-03T21:49:19.303 回答