gpt4 book ai didi

ruby-on-rails - ActiveRecord 查询以获取跨表的 SUM

转载 作者:行者123 更新时间:2023-12-04 04:47:52 25 4
gpt4 key购买 nike

我有以下模型:

# == 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 的查询接口(interface)来做这件事? (我正在使用 Rails 4。)


编辑:我已经有了以前通过 Quote 查询得到的 ActiveRecord 实例,所以我更愿意让我的查询从 quotes 表开始并加入 rates 表,而不是相反。像这样:

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

最佳答案

试试这个

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')

关于ruby-on-rails - ActiveRecord 查询以获取跨表的 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com