ruby-on-railsvalidationrails-activerecord

How do i specify and validate an enum in rails?


I currently have a model Attend that will have a status column, and this status column will only have a few values for it. STATUS_OPTIONS = {:yes, :no, :maybe}

1) I am not sure how i can validate this before a user inserts an Attend? Basically an enum in java but how could i do this in rails?


Solution

  • 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