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

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

提交回复
热议问题