Reputation: 113
I am using rails and mongoid gem. While using Enum in Mongoid model, with extend Enumerize
things works. But upon rendering data as JSON to front-end (eg. using ModelName.where(condition)
), the response for the enum field is not the string value of the enum but integer.
Example:
enumerize :field_name, in: { abc: 0, def: 5, ghi: 10 }, predicates: true, scope: :shallow
the rendered json looks like:
{
"model_name": {
"field_name": 5 //instead of "def"
}
}
Any help would be highly appreciated.
Upvotes: 1
Views: 740
Reputation: 269
This sounds similar to a question I answered a while back: Rails 5.2 API - Returning enum value in JSON
def as_json(options = {})
super.tap do |hash|
hash['field_name'] = ModelName::enum[field_name]
end
end
Upvotes: 2