我在将以下SQL查询转换为ActiveRecord查询时遇到了麻烦。 这将是原始SQL中的查询:
SELECT customers.name, customers.email, customers.address, (sales.quantity * sales.price AS total_spent)
FROM customers JOIN sales ON customers.id = sales.customer_id
GROUP BY customers.id
ORDER BY total_spent DESC
我这样做是为了开始为订购顶级客户而开始工作,但它不起作用:
Customer.joins(:buys).group("customers.id").select("id", "name", "price"*"stock" as "total_buys")
任何帮助都会非常感激。
感谢。
答案 0 :(得分:1)
首先设置你的模型关联并添加一些方便的方法
class Customer < ActiveRecord::Base
has_many :sales
# if you add a subtotal field that is autocalculated you could also do this
def total_spent
self.sales.all.map(|sale| sale.total ).sum
end
end
class Sale < ActiveRecord::Base
belongs_to :customer
def total
self.price * self.amount
end
end
然后在您的应用或控制台中输入:
Customer.first.sales.map(&:total).sum
或所有客户:
Customer.all.each{ |c| puts c.sales.map(&:total).sum }