2013-07-28 22 views
2

我有以下型號:ActiveRecord的查詢來獲取整個表的SUM

# == Schema Information 
# 
# Table name: quotes 
# 
# id      :integer   not null, primary key 
# bound_rate_id   :integer 
class Quote < ActiveRecord::Base 
    #snip 
end 

# == Schema Information 
# 
# Table name: rates 
# 
# id        :integer   not null, primary key 
# quoted_premium     :integer 
class Rate < ActiveRecord::Base 
    #snip 
end 

我想創建一個查詢,將計算出同樣的事情,因爲這循環:

sum = 0 
for quote in Quote.all 
    rate = Rate.find(quote.bound_rate_id) 
    sum += rate.quoted_premium 
end 

我會怎樣使用ActiveRecord的查詢界面來做到這一點? (我用Rails 4)


編輯:我已經從以前的查詢ActiveRecord情況下對Quote,所以我寧願從quotes表我的查詢開始,加入到rates表,而不是其他方式。就像這樣:

some_quotes = Quote.where(:some_other_property, my_param); 
sum_of_rates = some_quotes.????? 

回答

3

嘗試了這一點

sum = Rate.where(:id => Quote.pluck(:bound_rate_id).compact).sum(:quoted_premium) 

添加關係試試這個

sum = Quote.joins(:rate).sum('rates.quoted_premium') # it will get sum of all query's quoted_premium 

爲了得到一些特殊的附加的總和where子句

sum = Quote.joins(:rate).where(:bound_rate_id => [list of Rate ids]).sum('rates.quoted_premium') 

如果後你得到一個Mysql2::Error: Unknown column 'rates.bound_rate_id' in 'on clause'錯誤,請指定ActiveRecord應如何放在一起加入

sum = Quote.joins('INNER JOIN rates ON quotes.bound_rate_id = rates.id').sum('rates.quoted_premium') 
+0

感謝您的回答!不幸的是(我沒有在我的問題中說明這一點),我已經有查詢中的'ActiveRecord'實例到''quotes'表中,所以我寧願讓我的查詢從'quotes'表開始並加入到'率'表。 – Kevin

+0

@Kevin陳述兩個模型之間的關係。 –

+0

我看了看模型。它們都沒有明確定義的「belongs_to」,「has_many」或「belongs_to_and_has_many」關係,這些關係以編程方式關聯它們。我認爲我們「手動」建立了一個關係,每個'Quote'具有1或0個'Rate',每個'Rate'屬於一個'Quote'。 – Kevin