Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
Kamilski81 Avatar asked Nov 16 '11 05:11

Kamilski81


People also ask

How does enum work in Rails?

ActiveRecord::Enum was introduced in Rails 4.1. An enum is an attribute where the values map to integers in the database and can be queried by name. Enums also give us the ability to change the state of the data very quickly. This makes it easy to use enums in Rails and saves a lot of time by providing dynamic methods.


1 Answers

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), 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

like image 60
barnett Avatar answered Oct 04 '22 15:10

barnett