I am trying to figure out what is the best way to store an enum value in activerecord but convert it to a \'title\' for display in an app.
I.E.
Review Enum:
While I agree that @Godsaur answer is correct - I personally don't like the approach of storing integer values to represent meaningful string equivalents (provided that enough database indexing is made and/or the cost of querying strings in the DB engine is similar to that of querying integers).
My approach is usually storing the text values in the database (for easier understanding of DB records).
class MyModel < ActiveRecord::Base
STATUSES = HashWithIndifferentAccess.new({unverified: 'unverified', reviewed: 'reviewed', flagged: 'flagged'})
#the text values are similar to their symbols key
#you could also define additional attributes for each key if needed. Ex:
#STATUSES = {unverified: {title: 'Unverified Text Title', txt: 'unverified'}, ...}
# assuming a 'status' field
scope :unverified, -> { where(status: STATUSES[:unverified]) }
def unverified?
status == STATUSES[:unverified]
end
# Or
STATUSES.each do |sym, val|
define_method("#{sym}?") {status == val}
end
end
<%= MyModel::STATUSES[@my_model.status] %> or
<%= MyModel::STATUSES[@my_model.status].title %>