How can I have ActiveRecord's pluck also return the column name for rendering in json?

前端 未结 7 860
予麋鹿
予麋鹿 2020-12-29 02:34
def jsontest
   @users = User.all.limit(10)
   render json: @users
end

yields

{
...

\"id\": 7,
\"name\": \"Sage Smith\",
\"email\"         


        
7条回答
  •  一生所求
    2020-12-29 03:27

    vee's answer is good, but I have one caveat. select instantiates a User for every row in the result, but pluck does not. That doesn't matter if you are only returning a few objects, but if you are returning large batches (50, 100, etc) you'll pay a significant performance penalty.

    I ran into this problem, and I switched back to pluck:

    #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'])
    

    It's ugly, but it gets the hash you want, and fast.

    I've updated it to reflect Mike Campbell's comment on Oct 11.

提交回复
热议问题