Rails 5.2 API - Returning enum value in JSON

让人想犯罪 __ 提交于 2020-01-06 08:18:08

问题


I currently have a postgres enum type setup in my user columns as roles. It works as intended like so.

Example:

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

And the JSON response returns it as:

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

However, the role attribute is returning the key instead of the enum value. Is there a solution for this?


回答1:


Give this a try

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



回答2:


I'd do this way. In User model file

def role_id
  User.roles[self.role]
end

and then you role_id method



来源:https://stackoverflow.com/questions/55185267/rails-5-2-api-returning-enum-value-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!