简体   繁体   English

查询唯一属性列表

[英]Query list of unique attributes

I created a Ruby array ( Articles ) with an attribute ( category ) containing repeating preset values (eg one of the following: "Drink", "Main", "Side" ). 我创建了一个Ruby数组( Articles ),其中包含重复预设值的属性( 类别 )(例如,以下之一: “Drink”,“Main”,“Side” )。 As result I'd like to get a list of all unique values of this category attribute. 因此,我想获得此类别属性的所有唯一值的列表。

I thought about something like 我想到了类似的东西

Article.all.category.uniq 

...but that didn't work. ......但那没用。 Here's an example array: 这是一个示例数组:

[#<Article id: 1, category: "Drink">, #<Article id: 2, category: "Main">, #<Article id: 3, category: "Drink">, #<Article id: 4, category: "Side">, #<Article id: 5, category: "Drink">, ] 

the content of the result list I am looking for should be in this case: "Drink", "Main", "Side" 我正在寻找的结果列表的内容应该是这样的: “饮料”,“主要”,“侧面”

Article.all.map {|a| a.category}.uniq

应该做的工作。

I'd do it like this: 我这样做:

Article.select("distinct category").map {|a| a.category}

rather than lucapette's answer , because that kind of operations are far slower in ruby than in a database. 而不是lucapette的答案 ,因为这种操作在ruby中比在数据库中慢得多。

My code example is assuming that you're using some kind of SQL database by the way. 我的代码示例假设您正在使用某种SQL数据库。 It would look different with other kinds of databases. 它与其他类型的数据库看起来不同。

在Rails 3.2中

Article.uniq.pluck(:category)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM