Rails 5.2 API-以JSON返回枚举值 [英] Rails 5.2 API - Returning enum value in JSON
本文介绍了Rails 5.2 API-以JSON返回枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前在我的用户列中有一个Postgres枚举类型设置为roles
.像预期的那样工作.
I currently have a postgres enum type setup in my user columns as roles
. It works as intended like so.
示例:
class User < ApplicationRecord
enum role: { admin: "Admin", viewer: "Viewer" }
end
并且JSON响应将其返回为:
And the JSON response returns it as:
{
"id": 1,
"role": "admin"
}
但是,role
属性将返回键而不是枚举值.有解决方案吗?
However, the role
attribute is returning the key instead of the enum value. Is there a solution for this?
推荐答案
尝试一下
def as_json(options = {})
super.tap do |hash|
hash['role'] = User::roles[role]
end
end
这篇关于Rails 5.2 API-以JSON返回枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文