1

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

这是我的 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 查询,它给出了所需的输出。

任何帮助,将不胜感激。

谢谢。

4

2 回答 2

3

Rails 控制台使用检查方法来显示对象内容。此方法不显示自定义字段的值。您将能够通过显式引用它在控制台上打印自定义属性的值。

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

编辑2

您需要用于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")
于 2013-03-15T07:43:55.137 回答
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
于 2013-03-15T07:36:43.853 回答