Ruby-on-Rails:从模型中选择不同的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18004239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:27:39  来源:igfitidea点击:

Ruby-on-Rails: Selecting distinct values from the model

ruby-on-railsrails-activerecord

提问by Bryan Wolfford

The docs: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

文档:http: //guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

Clearly state that:

明确指出:

query = Client.select(:name).distinct
# => Returns unique names

However, when I try that in my controller, I get the following error:

但是,当我在控制器中尝试时,出现以下错误:

undefined method `distinct' for #<ActiveRecord::Relation:0xb2f6f2cc>

To be clear, I want the distinct names, like ['George', 'Brandon'], not the clients actual records. Is there something that I am missing?

明确地说,我想要不同的名字,比如 ['George', 'Brandon'],而不是客户的实际记录。有什么我想念的吗?

回答by Shadwell

The .distinctoption was added for rails 4 which is what the latest guides refer to.

.distinct选项是为 rails 4 添加的,这是最新指南所指的内容。

Rails 2

导轨 2

If you are still on rails 2 you will need to use:

如果您仍在使用 rails 2,则需要使用:

Client.select('distinct(name)')

Rails 3

导轨 3

If you are on Rails 3 you will need to use:

如果您使用 Rails 3,则需要使用:

Client.select(:name).uniq

If you look at the equivalent section of the rails 3 guideyou can see the difference between the two versions.

如果您查看rails 3 指南的等效部分,您可以看到两个版本之间的差异。

回答by Малъ Скрылевъ

There are some approaches:

有一些方法:

  1. Rails way:

    Model.select(:name).distinct
    
  2. Semi-rails way

    Model.select("DISTINCT ON(models.name) models.*")
    

    The second allows you to select the first record uniqued by name, but in the whole matter, not only names.

  1. 导轨方式:

    Model.select(:name).distinct
    
  2. 半轨方式

    Model.select("DISTINCT ON(models.name) models.*")
    

    第二个允许您选择按名称唯一的第一条记录,但在整个事件中,不仅是名称。

回答by Santhosh

This will work for Rails 2 (pretty old rails I know!), 3 and 4.

这将适用于 Rails 2(我知道很旧的 rails!)、3 和 4。

Client.select('distinct(name)')

This will actually use the SQL select distinct statement

这实际上将使用 SQL select distinct 语句

SELECT distinct name FROM clients

SELECT distinct name FROM clients

回答by David Aldridge

If you do not want ActiveRecord::Relations returned, just an array of the names as strings, then use:

如果您不想返回 ActiveRecord::Relations,只需将名称数组作为字符串,然后使用:

Client.distinct.pluck(:name)

To get an ordered result set:

获取有序结果集:

Client.order(:name).distinct.pluck(:name)