Rails 5.2 API - 返回 JSON 中的枚举值

Rails 5.2 API - Returning enum value in JSON

我目前在我的用户列中有一个 postgres 枚举类型设置为 roles。它像这样按预期工作。

示例:

class User < ApplicationRecord
  enum role: { admin: "Admin", viewer: "Viewer" } 
end

JSON 响应 returns 为:

{
  "id": 1,
  "role": "admin"
}

但是,role 属性返回键而不是枚举值。有解决办法吗?

我会这样做。在 User 模型文件中

def role_id
  User.roles[self.role]
end

然后你role_id方法

试试这个

def as_json(options = {})
  super.tap do |hash|
    hash['role'] = User::roles[role]
  end
end