Ruby-on-Rails:从模型中选择不同的值 [英] Ruby-on-Rails: Selecting distinct values from the model

查看:28
本文介绍了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.

这篇关于Ruby-on-Rails:从模型中选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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