gpt4 book ai didi

ruby-on-rails - 使用 Active Record 对关联表求和

转载 作者:行者123 更新时间:2023-12-04 06:16:45 25 4
gpt4 key购买 nike

如何对关联中的所有“总计”列求和?

我的 SQL-fu 很烂,所以我想学习如何在我的 rails 2.3.5 应用程序中使用 Active Record(所以请不要使用花哨的语法 ;-) 我在 MySQL 上。

假设我有:


Shop

has_many :customers
has_many :transactions, :through => :customers

很正常的东西。


shop = Shop.first
shop.transactions
=> 100

好的,问题的所有背景:

我想对过去一年(2010 年 1 月 1 日至 2010 年 12 月 31 日)交易中的 total 列求和,并按客户显示。

虽然我知道如何对事务进行分组并根据条件查找,但这是我缺乏 SQL 让我失望的总和部分。


first = Date.new(2010, 01, 01)
last = Date.new(2010, 12, 31)

shop.transactions(:conditions => {:created_at => first..last}, :group => :customer_id, :include => sum(:total))

我刚刚中了一个刺,我在正确的 rails 上吗?

最佳答案


shop.transactions.sum(:total, :conditions => {:created_at => first..last}, :group => :customer_id)

这看起来是一种更简单的方法。我现在知道 sum 也可以采用 AR 属性。很酷。

关于ruby-on-rails - 使用 Active Record 对关联表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com