Rails rails tricks: pluck (ActiveRecord)

luoping0425 · June 21, 2012 · Last by lgn21st replied at June 21, 2012 · 4418 hits

参考:http://guides.rubyonrails.org/active_record_querying.html#pluck

pluck can be used to query a single column from the underlying table of a model. It accepts a column name as argument and returns an array of values of the specified column with the corresponding data type.

pluck 能用来查询来自于一个 model 的基础表的单列,它接受一个列名作为参数,返回特定列的对应值的一个数组。

Example:

Client.where(:active => true).pluck(:id)
=># select id from clients where active = 1

Client.uniq.pluck(:role)
=># select distinct role from clients  

pluck makes it posspible code like

pluck 类似于下面的代码:

Client.select(:id).map { |c| c.id }

with

即:

Client.pluck(:id)

说明:最近在整理项目,发现很多冗余的代码,顺手整理一下,以上这段是从 rails guides 中翻译的,本来想放到 rails guides,但目前自己占了个翻译的坑还没完成就没好意思,先贴这。 关于 tricks,我是想把一些大家平常不太注意的比较少用的一些技巧(或不算技巧)。当然也是比较简单的一些东西。

建议按 Markdown 格式 排排版~

贴代码要加高亮啊

Unknow user #3 June 21, 2012

今天刚看了这个技巧就用上了。以前我查看用户的 email 列表这样做:Member.all.map(&:email) 现在这样:Member.pluck(:email) 对应到 sql 语句分别是 select * 和 select email. 可能速度会有提升,另外就是代码短了些. 还是比较有用的。

Underscore.js 里面也有对应的方法:http://underscorejs.org/#pluck

You need to Sign in before reply, if you don't have an account, please Sign up first.