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

前端 未结 7 827
予麋鹿
予麋鹿 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:10

    You can pull the data along with the column name as:

    @users = User.all.limit(10)
                     .pluck(:id, :name, :email, :created_at)
                     .map {|id, name, email, created_at| { id: id, name: name, 
                                                           email: email, 
                                                           created_at: created_at } }
    

    This will pull the data and map it according to how you want it. One advantage of using pluck over select is that you can use joins along with it.

    0 讨论(0)
  • 2020-12-29 03:18

    @girishso's gem is great, but my project is in Rails 3. It doesn't work.

    This article is helpful to me, or install pluck_all gem to achieve this.

    Usage:

    User.limit(10).pluck_all(:id, :name, :email, :created_at)
    
    0 讨论(0)
  • 2020-12-29 03:19

    Fastest way to return hash of users with selected columns is use ActiveRecord::Base.connection.select_all method.

    sql = User.select('id, name, email, created_at').limit(10).to_sql
    @users = ActiveRecord::Base.connection.select_all(sql)
    render json: @users
    
    0 讨论(0)
  • 2020-12-29 03:23

    @andrewCone - It should be like this:

    User.limit(:10).pluck_to_hash([:id, :name, :email, :created_at])
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 03:32

    Created a simple pluck_to_hash gem to achieve this. https://github.com/girishso/pluck_to_hash

    Usage example..

    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}]
    #
    
    0 讨论(0)
提交回复
热议问题