ActiveRecord Query以跨表获取SUM

时间:2013-07-28 18:47:23

标签: ruby-on-rails rails-activerecord ruby-on-rails-4

我有以下型号:

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

1 个答案:

答案 0 :(得分: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')