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.?????
感謝您的回答!不幸的是(我沒有在我的問題中說明這一點),我已經有查詢中的'ActiveRecord'實例到''quotes'表中,所以我寧願讓我的查詢從'quotes'表開始並加入到'率'表。 – Kevin
@Kevin陳述兩個模型之間的關係。 –
我看了看模型。它們都沒有明確定義的「belongs_to」,「has_many」或「belongs_to_and_has_many」關係,這些關係以編程方式關聯它們。我認爲我們「手動」建立了一個關係,每個'Quote'具有1或0個'Rate',每個'Rate'屬於一個'Quote'。 – Kevin