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

前端 未结 7 831
予麋鹿
予麋鹿 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: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}]
    #
    

提交回复
热议问题