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

Viewed 21076
def jsontest
   @users = User.all.limit(10)
   render json: @users
end

yields

{
...

"id": 7,
"name": "Sage Smith",
"email": "example-6@railstutorial.org",
"created_at": "2013-10-17T02:29:15.638Z",
"updated_at": "2013-10-17T02:29:15.638Z",
"password_digest": "$2a$10$taHk3udtWN61Il5I18akj.E90AB1TmdL1BkQBKPk/4eZ7YyizGOli",
"remember_token": "118f807d0773873fb5e4cd3b5d98048aef4f6f59",
"admin": false

...
}

But I would like to omit certain certain fields from this API, so I use pluck

def jsontest
  @users = User.all.limit(10).pluck(:id, :name, :email, :created_at) ###
  render json: @users
end

but pluck returns an array of only values, when I would like to have each object's attributes accessible by hash key.

[
...

    7,
    "Sage Smith",
    "example-6@railstutorial.org",
    "2013-10-17T02:29:15.638Z"

...    

]

So how can I effectively pluck the values and their keys?

I realize I could sweep through @users and grab the keys before plucking and recreate the hash, but I'm expecting there to be some convenience method that does exactly what I want.

7 Answers

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.

Related