Ruby on rails Rails 5-具有uniq属性的查询记录
我正在使用Rails 5和Postgresql。 以前版本的Rails(包括Rails4,使用distinct、uniq等)已经回答了这个问题,但是Rails5对我来说都不起作用,因为它们已经贬值了 我有一个Ruby on rails Rails 5-具有uniq属性的查询记录,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,我正在使用Rails 5和Postgresql。 以前版本的Rails(包括Rails4,使用distinct、uniq等)已经回答了这个问题,但是Rails5对我来说都不起作用,因为它们已经贬值了 我有一个Upload模型,它有一个uuid属性。 我想从枚举中获取具有不同uuid的记录,而不使用uniq 这是我最初的疑问: Upload.includes(:user, product: [:catalog]).where(file_type: "product_attachment", pro
Upload
模型,它有一个uuid
属性。
我想从枚举中获取具有不同uuid
的记录,而不使用uniq
这是我最初的疑问:
Upload.includes(:user, product: [:catalog]).where(file_type: "product_attachment", product_id: nil, user_id: current_user.id))
我在添加distinct
或select
时出错(这些方法似乎经常用于从模型中只返回一个属性,而我在这里需要整个对象)
有没有关于如何在Rails 5中实现这一点的想法
使用示例数据编辑:
上载:
id: 1
uuid: 8e8fece82b6b1368ab6f21852c625e85718d210e
id: 2
uuid: 842e7650b4bba97f097d9cf57f47d8160086b7cd
id: 3
uuid: 8e8fece82b6b1368ab6f21852c625e85718d210e
上载1和3具有相同的uuid,因此预期结果将仅包含id为1和2(具有不同uuid)的上载。您可以使用
组代码>它提供所有不同的记录,而不使用uniq:
ABC.group(:uuid)
假设您希望对每个重复的uuid
组使用最小id
上传
Upload.includes(:user, product: [:catalog]).where(file_type: "product_attachment", product_id: nil, user_id: current_user.id)).
where(id: Upload.group(:uuid).select("min(id)"))
要分解它,这个where
子句过滤所有具有重复uuid
的Upload
,除了具有min
id
where(id: Upload.group(:uuid).select("min(id)"))
您能否创建表中数据和预期结果的最小示例?您可以使用select like so Upload.select(DISTINCT ON(uploads.uuid),uploads.*)
或使用类似于横向连接的方法。@max刚刚用更具体的example@max我已经尝试了一个类似于您的查询的select,我得到了以下错误:ActiveRecord::StatementInvalid:PG::SyntaxError:error:SyntaxError位于或接近“,”第1行:选择DISTINCT ON(uploads.uuid),uploads.*FROM“uploads”