2

我有以下型号:

# == 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.?????
4

1 回答 1

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

得到一些特定的 add 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')
于 2013-07-28T19:00:16.517 回答