mysql - 将 mysql 查询移动到模型

标签 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"
            }   

将以下代码放入此 Controller 的索引操作中是可行的,但绝对不是正确的方法!

@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

数据库 )

最佳答案

我假设您的模型名称是 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

关于mysql - 将 mysql 查询移动到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212200/

相关文章:

ruby-on-rails - 基于数据库信息的动态CSS

php - 这是共享和关闭 PDO 连接的正确方法吗?

mysql - 插入 - 不存在的地方

ruby-on-rails - 在Rails 3.1 App中使用更少

ruby-on-rails - 设计 - 将 OAuth 与现有帐户合并

ruby-on-rails - rails : Is that possible to define named scope in a module?

ruby-on-rails - rails 3 : Auto-populating a table upon new user creation with Devise

mysql 存储过程输出多列

java - 通讯链接失败 Caused by : java.net.SocketException : Connection reset.

ruby-on-rails - 为什么 Rails 数据库 ID 在销毁中间项后继续向前计数?