How do i specify and validate an enum in rails?

前端 未结 8 1701
南笙
南笙 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 21:02

    What we have started doing is defining our enum items within an array and then using that array for specifying the enum, validations, and using the values within the application.

    STATUS_OPTIONS = [:yes, :no, :maybe]
    enum status_option: STATUS_OPTIONS
    validates :status_option, inclusion: { in: STATUS_OPTIONS.map(&:to_s) }
    

    This way you can also use STATUS_OPTIONS later, like for creating a drop down lists. If you want to expose your values to the user you can always map like this:

    STATUS_OPTIONS.map {|s| s.to_s.titleize }
    
    0 讨论(0)
  • 2020-12-30 21:04

    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

    0 讨论(0)
提交回复
热议问题