How do i specify and validate an enum in rails? How do i specify and validate an enum in rails? ruby-on-rails ruby-on-rails

How do i specify and validate an enum in rails?


Now that Rails 4.1 includes enums you can do the following:

class Attend < ActiveRecord::Base    enum size: [:yes, :no, :maybe]    # also can use the %i() syntax for an array of symbols:    # %i(yes no maybe)    validates :size, inclusion: { in: sizes.keys }end

Which then provides you with a scope (ie: Attend.yes, Attend.no, Attend.maybe for each a checker method to see if certain status is set (ie: #yes?, #no?, #maybe?), along with attribute setter methods (ie: #yes!, #no!, #maybe!).

Rails Docs on enums


Create a globally accessible array of the options you want, then validate the value of your status column:

class Attend < ActiveRecord::Base  STATUS_OPTIONS = %w(yes no maybe)  validates :status, :inclusion => {:in => STATUS_OPTIONS}end

You could then access the possible statuses via Attend::STATUS_OPTIONS


This is how I implement in my Rails 4 project.

class Attend < ActiveRecord::Base    enum size: [:yes, :no, :maybe]    validates :size, inclusion: { in: Attend.sizes.keys }end

Attend.sizes gives you the mapping.

Attend.sizes # {"yes" => 0, "no" => 1, "maybe" => 2}

See more in Rails doc