Rails 4.1 added support for Enums to be used in models. You can check out the release notes here.
Generally, these are supposed to be used for tracking internal states and should not be exposed to the user. If you're a rebel, however, you can easily use these for user-definable states.
Let's say you have a User model. We define the enum as follows:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :encrypted_password
# ...
t.integer :role
end
end
First, we create a constant for our list of semesters, then create a friendly, human-readable version for displaying to the user.
class User > ActiveRecord::Base
enum role: %i[admin moderator user banned]
ROLE_SELECT = roles.map {|r| [r.to_s.titleize, roles.index(r)] }
end
Using SimpleForm, we can use either a select
box or radio buttons to pick our options.
= simple_form_for @user do |f|
= f.input :role, as: :select, collection: User.const_get(:ROLE_SELECT), selected: User.roles[@user.role]
Easy peasy!
API: http://api.rubyonrails.org/classes/ActiveRecord/Enum.html