我正在尝试在具有范围的 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.13
和Postgres 9.4.12
。任何帮助表示赞赏。