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

前端 未结 7 826
予麋鹿
予麋鹿 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.

提交回复
热议问题