多和()S在ActiveRecord的Rails中 [英] Multiple sum()s in ActiveRecord in Rails

查看:145
本文介绍了多和()S在ActiveRecord的Rails中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,而选择其他的领域,同时通过链接多个和(),以一个组。我还preFER手动使用ActiveRecord的方法来做到这一点,而不是构建一个SQL字符串,因为我可以修改的ActiveRecord的继承的类后。

I'd like to link multiple sums() to a single group by while selecting other fields at the same time. I'd also prefer to use the ActiveRecord methods to do this rather than construct a sql string manually, as I may modify the behavior of inherited classes of ActiveRecord later.

例如,我想重新present语句(作为一个例子)

For example I'd like to represent the statement (as an example)

select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id

的东西,如:

with something like:

LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)

的原因是我以后可能会添加其他组停车处并在从句,其中所有的款项都会有共通之处。

The reason being I may add additional group-bys and where-clauses later, which all the sums will have in common.

推荐答案

这对我的作品:

require "active_record"
require "logger"

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection :adapter => "postgresql", :database => "francois"

ActiveRecord::Base.connection.execute "DROP TABLE IF EXISTS values"
ActiveRecord::Base.connection.execute "CREATE TABLE values(user_id INTEGER NOT NULL, quantity INTEGER NOT NULL DEFAULT 1, cost INTEGER NOT NULL DEFAULT 2)"

class Value < ActiveRecord::Base
end

2.times do
  5.times do |n|
    Value.create!(:user_id => n)
  end
end

Value.group(:user_id).select('user_id, SUM(cost) AS total_cost, SUM(quantity) AS total_quantity').each do |value|
  p [value.user_id, value.total_quantity, value.total_cost]
end

我试过和(:成本:量),而 #sum 不期望的参数定义了此方法。我也试过和(:成本=>:total_cost,:量=>:total_quantity)。,都无济于事。

I tried sum(:cost, :quantity), but #sum doesn't expect arguments defined this way. I also tried sum(:cost => :total_cost, :quantity => :total_quantity), to no avail.

这篇关于多和()S在ActiveRecord的Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆