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

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

问题描述

def jsontest@users = User.all.limit(10)渲染 json:@users结尾

收益

<代码>{...身份证":7,"name": "圣人史密斯","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",管理员":假...}

但我想从这个 API 中省略某些字段,所以我使用 pluck

def jsontest@users = User.all.limit(10).pluck(:id, :name, :email, :created_at) ###渲染 json:@users结尾

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

<预><代码>[...7、圣人史密斯","example-6@railstutorial.org",2013-10-17T02:29:15.638Z"...]

那么我怎样才能有效地提取值和它们的键呢?

我意识到我可以在提取和重新创建哈希之前扫过@users 并获取密钥,但我希望有一些方便的方法可以完全满足我的需求.

解决方案

使用select代替pluck:

def jsontest@users = User.select('id, name, email, created_at').limit(10)渲染 json:@users结尾

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.

解决方案

Use select instead of pluck:

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

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

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