1

我正在尝试在具有范围的 Rails 中使用 distinct on,我在我的模型中创建了一个方法,如下所示:

def self.fetch_most_recent_by_user(scope)
  scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end

当我执行此操作时,我得到如下错误:

TestModel.fetch_most_recent_by_user(TestModel.includes(:user))

ERROR:  syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...

在搜索时,DISTINCT ON我发现它应该是 postgres 使其工作的 select 语句中的第一个元素。

我想DISTINCT ON在 select 语句中添加。我尝试清除except(:select)这里获得的旧选择语句,但它不起作用,因为includes(:user)在进行左连接时先添加用户属性。

我正在使用Rails 4.0.13Postgres 9.4.12。任何帮助表示赞赏。

4

1 回答 1

0

我发现如果包含干预了不同的我的子查询,因为它DISTINCT ON失败了。我将我的方法修改为这个并且它有效:

  def self.fetch_most_recent_eld_log_by_user(scope, include_associations = { })
    scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) eld_logs.user_id, eld_logs.guid").order("eld_logs.user_id, eld_logs.created_at desc").map(&:guid))
        .includes(include_associations)
  end

如果有人可以提供一种在活动记录范围的选择语句中添加某些内容的方法,那仍然会很好。

于 2017-07-09T09:28:34.803 回答