Best way to store Enum value in ActiveRecord and convert to string for display
rails-activerecord, ruby-on-rails
Solution
ActiveRecord enums is the best way to go since it's a part of the framework (since version 4.1).
Its usage is quite simple:
Migration:
class AddEnumToMyModel < ActiveRecord::Migration
def change
add_column :my_model, :status, :integer, default: 0
end
end
Model:
class MyModel < ActiveRecord::Base
enum status: [:draft, :beta, :public]
end
Then use it a will:
MyModel.draft # gets all drafts
MyModel.last.draft? # checks if the last model is draft
MyModel.last.status # gets the string description of the status of my model
For mode information refer to documentation.
Problem
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: ``` UNREVIEWED = {:title => "Unreviewed", :name => "UNREVIEWED"} REVIEWED = {:title => "Reviewed", :name => "REVIEWED"} FLAGGED = {:title => "Flagged as inappropriate", :name => "FLAGGED"} ``` So in java land I was used to storing the ENUMs name ie (REVIEWED) in the database and then converting that name into that actual enum on the server such that I could call helper methods on it, ie: ``` review = Review.valueOf(review) review.title() ``` Is there something similar I can do in rails to accomplish this? FYI we are trying to keep our app super small so if I can easily accomplish this or something similar without a GEM that would be great. Any 'standard' way to do this, as I imagine I am not the first to struggle with this issue? Thanks!