Rails 4通过单个属性唯一查询 [英] Rails 4 query unique by single attribute

查看:82
本文介绍了Rails 4通过单个属性唯一查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,这比任何其他问题都更像是一个领域问题,但这是我要尝试的事情。



我有三个对象,称为物品

 <项目ID:1,名称:'Book'> 
<商品ID:2,名称: Car>
<商品ID:3,名称: Book>

我想执行一个查询,该查询仅返回每个唯一的名称属性之一。 / p>

类似于 Item.select('distinct(name),items。*')

$ b之类的东西
$ b

尽管这不起作用,它仍会返回所有三个项目。



如何形成此查询,使其仅返回:

 <商品ID:1,名称:'Book'> 
<商品ID:2,名称: Car>


解决方案

如果要恢复整个模型,但是仍然保持唯一性,您可以使用以下方法:

  Item.select('(name(distantt on(name)*')distinct on(name)*'))

我仅使用Postgres数据库对此进行了测试。


So this is more of an arel question than anything but here's what I am trying to do.

I have three objects lets say, called Items

<Item id: 1, name: 'Book'>
<Item id: 2, name: 'Car'>
<Item id: 3, name: 'Book'>

I want to do a query that will just return only one of each unique "name" attributes.

Something like Item.select('distinct(name), items.*')

This doesn't work though, it still returns all three items.

How can I form this query so that it only returns:

<Item id: 1, name: 'Book'>
<Item id: 2, name: 'Car'>

解决方案

If you want to get the entire model back, but still maintain uniqueness, you can use this:

Item.select('distinct on (name) *')

I've only tested this with a Postgres database. It may or may not work with mysql.

这篇关于Rails 4通过单个属性唯一查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆