How do i specify and validate an enum in rails?

前端 未结 8 1851
南笙
南笙 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:42

    To define dynamic behavior you can use in: :method_name notation:

    class Attend < ActiveRecord::Base
      enum status: [:yes, :no, :maybe]
      validates :status, inclusion: {in: :allowed_statuses}
    
      private
    
      # restricts status to be changed from :no to :yes
      def allowed_statuses
        min_status = Attend.statuses[status_was]
        Attend.statuses.select { |_, v| v >= min_status }.keys
      end
    end
    

提交回复
热议问题