从Rails中的多个表中选择总和结果

时间:2013-03-15 07:30:11

标签: ruby-on-rails ruby-on-rails-3 postgresql activerecord

我在Rails控制台中工作。我想在两个不同的表中选择相同命名列的SUM。

这是我的ActiveRecord代码:

Computer.joins(:services, :repairs)
.select("computers.id, SUM(services.cost) as SCOST, SUM(repairs.cost) as RCOST")
.group("computers.id")

这很好用并返回以下正确的SQL:

`SELECT computers.id, SUM(services.cost) as SCOST, SUM(repairs.cost) as RCOST 
FROM "computers" INNER JOIN "services" ON "services"."computer_id" = "computers"."id" 
INNER JOIN "repairs" ON "repairs"."computer_id" = "computers"."id" 
GROUP BY computers.id `

但它在Rails控制台中给出了以下结果:

=> [#<Computer id: 36>, #<Computer id: 32>]

我不应该也能访问我的SUM值吗?我在postgres中运行了上面的SQL查询,它给出了所需的输出。

任何帮助都将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:2)

Rails控制台使用inspect方法显示对象内容。此方法不显示自定义字段的值。您可以通过明确引用它来在控制台上打印自定义属性的值。

Computer.joins(:services, :repairs)
.select("computers.id, SUM(services.cost) as scost, SUM(repairs.cost) as rcost")
.group("computers.id").each do |c|
  puts c.scost
  puts c.rcost
end

修改

基于评论的示例:

在控制器中创建一个成员变量:

@computers = Computer.joins(:services, :repairs)
.select("computers.id, SUM(services.cost) as scost, SUM(repairs.cost) as rcost")
.group("computers.id")

迭代视图中的变量

- @computers.each do |computer| 
  = computer.scost
  = computer.rcost

<强> EDIT2

您需要使用LEFT OUTER JOIN来获取缺少维修或服务的计算机的值。

join_sql = "LEFT OUTER JOIN services ON services.computer_id = computers.id
            LEFT OUTER JOIN repairs ON repairs.computer_id = computers.id"
sum_sql  = "SUM(COALESCE(services.cost, 0)) as scost, 
            SUM(COALESCE(repairs.cost, 0)) as rcost"

@computers = Computer.joins(join_sql)
.select("computers.id, #{sum_sql}")
.group("computers.id")

答案 1 :(得分:0)

尝试如下,

@computer_list = Computer.joins(:services, :repairs).select("computers.id, SUM(services.cost) as SCOST, SUM(repairs.cost) as RCOST").group("computers.id")
@computer_list.last.SCOST