vee的答案很好,但我有一点需要注意.为结果中的每一行select
实例化a User
,但pluck
不是.如果你只返回一些对象并不重要,但是如果你要返回大批量(50,100等),你将会付出很大的性能损失.
我遇到了这个问题,然后我又回到了采摘:
#in user.rb def self.pluck_to_hash(keys) pluck(*keys).map{|pa| Hash[keys.zip(pa)]} end #in elsewhere.rb User.limit(:10).pluck_to_hash(['id, name, email, created_at'])
这很丑陋,但它可以获得你想要的哈希,而且速度很快.
我更新了它以反映Mike Campbell在10月11日的评论.
vee的答案很好,但我有一点需要注意.为结果中的每一行select
实例化a User
,但pluck
不是.如果你只返回一些对象并不重要,但是如果你要返回大批量(50,100等),你将会付出很大的性能损失.
我遇到了这个问题,然后我又回到了采摘:
#in user.rb def self.pluck_to_hash(keys) pluck(*keys).map{|pa| Hash[keys.zip(pa)]} end #in elsewhere.rb User.limit(:10).pluck_to_hash(['id, name, email, created_at'])
这很丑陋,但它可以获得你想要的哈希,而且速度很快.
我更新了它以反映Mike Campbell在10月11日的评论.
使用select
而不是pluck
:
def jsontest @users = User.select('id, name, email, created_at').limit(10) render json: @users end
创造了一个简单的pluck_to_hash
宝石来实现这一目标.
https://github.com/girishso/pluck_to_hash
用法示例..
Post.limit(2).pluck_to_hash([:id, :title]) # # [{:id=>213, :title=>"foo"}, {:id=>214, :title=>"bar"}] # Post.limit(2).pluck_to_hash(:id) # # [{:id=>213}, {:id=>214}] # # Or use the shorter alias pluck_h Post.limit(2).pluck_h(:id) # # [{:id=>213}, {:id=>214}] #