pja*_*mer 3 activerecord ruby-on-rails
如何将一个关联中的所有"总"列相加?
我的SQL-fu糟透了,所以我想学习如何使用Active Record for my rails 2.3.5应用程序(所以没有花哨的语法,只是请;-)而且我在MySQL上.
比方说我有:
Shop
has_many :customers
has_many :transactions, :through => :customers
Run Code Online (Sandbox Code Playgroud)
很正常的东西.
shop = Shop.first
shop.transactions
=> 100
Run Code Online (Sandbox Code Playgroud)
好的,问题的所有背景:
我想total在过去一年(2010年1月1日,2010年12月31日)的交易中对该列进行总结,并按客户显示.
虽然我知道如何对事务进行分组并找到条件,但这是我缺少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))
Run Code Online (Sandbox Code Playgroud)
我只是刺了一下,我是在正确的轨道上吗?
shop.transactions.sum(:total, :conditions => {:created_at => first..last}, :group => :customer_id)
Run Code Online (Sandbox Code Playgroud)
这看起来更简单.我现在知道sum也可以采用AR属性.凉.