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

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

问题描述:

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

明确说明:

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>

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

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

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

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

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

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

Client.select('distinct(name)')

轨道 3

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

Rails 3

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

Client.select(:name).uniq

如果您查看 Rails 3 指南的等效 部分你可以看到两个版本的区别.

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