Rails 4 JOIN GROUP BY和SELECT

时间:2015-05-04 13:26:49

标签: sql ruby-on-rails join

我正在尝试在Rails 4中加入2个表,以执行计数并保留连接表的列。

模型:用户has_many:订单

我想要的:订单数量和最后一个订单的日期。

has_many :orders, -> { select("users.*, count(orders.id) as orders_count").group('users.id') }

我想在ORDERS表中选择created_at列,如此

select("users.*, orders.created_at, count(orders.id) as orders_count").group('users.id')

但在那种情况下我收到错误

PG::GroupingError: ERROR:  column "orders.created_at" must appear in the GROUP BY clause or be used in an aggregate function

我需要FIRST created_at所以我在created_at列上尝试了SQL Aggregate Function“FIRST”

select("users.*, first(orders.created_at) as most_recent, count(orders.id) as orders_count").group('users.id')

但我会得到

PG::UndefinedFunction: ERROR:  function first(character varying) does not exist

任何想法如何在连接表上实现此JOIN,COUNT和SELECT?

1 个答案:

答案 0 :(得分:3)

以下是否适合您?

User.joins(:orders)
    .select("users.*, max(orders.created_at) as most_recent, count(orders.id) as orders_count")
    .group('users.id')

获取max的{​​{1}}应该会显示最近订单的日期。我认为您不希望将order.created_at作为select订单的一部分,因为您正在查找用户列表,而不是订单列表。如果您有一个返回此有效记录查询的方法,假设您将多次使用它,则可以将以下内容添加到has_many模型中。

User

然后,你可以使用以下方法调用该方法:

def self.with_order_info
  self.joins(:orders)
      .select("users.*, max(orders.created_at) as most_recent, count(orders.id) as orders_count")
      .group('users.id')
end

作为进一步的说明(要100%明确),您应该将您的订单与订单保持联系:

@users = User.with_order_info