新手问题 关于 ActiveRecord 如何提取一个字段?

topswim · March 12, 2013 · Last by topswim replied at March 13, 2013 · 2729 hits

在用 ActiveRecord 的时候比如我想取 user 表的姓名的字段,user.all.name 没有这种方法,我又不想自己把它遍历一边。ActiveRecord 有什么好的方法吗?

User.select(:name).where(blabla..)

看到Users.all就 233 了,服务器当场卡死。。

为什么你想要得到遍历的结果但是不想遍历? User.all.map{ |user| user.name }

性能最好的是 User.pluck(:name)

老版本没 pluck 就是 User.select(:name).map(&:name)

#3 楼 @ch3n 对啊!看来我的思维还不是 ruby 的。

#6 楼 @topswim 3 楼会爆内存,你的想法是对的

use find_each or find_in_batches so Rails can help you to iterate all records but in batches, it will improve query performance. see documents here in details.

but pluck is better in your case.

User.collect(&:name) 何如?

#7 楼 @Rei #8 楼 @nightire 我想问问这个 twitter-bootstrap-rails gem 和 bootstrap gem 有什么区别啊?

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