问题
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