我怎样才能有ActiveRecord的采摘还返回列名称以呈现在json中? [英] How can I have ActiveRecord's pluck also return the column name for rendering in json?

查看:44
本文介绍了我怎样才能有ActiveRecord的采摘还返回列名称以呈现在json中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

收益

{
...

"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

...
}

但是我想从此API中省略某些字段,所以我使用

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

但是当我想让每个对象的属性可以通过哈希键访问时,pluck返回一个只有值的数组。

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?

我意识到我可以扫遍@users并在拔出并重新创建哈希值之前抓取密钥,但是我希望有一些方便的方法可以完全满足我的要求。

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.

推荐答案

使用 select 代替 pluck

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

这篇关于我怎样才能有ActiveRecord的采摘还返回列名称以呈现在json中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆