How do i specify and validate an enum in rails?

前端 未结 8 1829
南笙
南笙 2020-12-30 20:15

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)

8条回答
  •  遥遥无期
    2020-12-30 20:40

    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

提交回复
热议问题