Rails enum validation not working but raise ArgumentError

后端 未结 2 1808
盖世英雄少女心
盖世英雄少女心 2021-01-06 00:24

A thread was created here, but it doesn\'t solve my problem.

My code is:

course.rb

class Course < ApplicationRecord
  COU         


        
2条回答
  •  执念已碎
    2021-01-06 00:47

    I've found a solution. Tested by myself in Rails 6.

    # app/models/contact.rb
    class Contact < ApplicationRecord
      include LiberalEnum
    
      enum kind: {
        phone: 'phone', skype: 'skype', whatsapp: 'whatsapp'
      }
    
      liberal_enum :kind
    
      validates :kind, presence: true, inclusion: { in: kinds.values }
    end
    
    # app/models/concerns/liberal_enum.rb
    module LiberalEnum
      extend ActiveSupport::Concern
    
      class_methods do
        def liberal_enum(attribute)
          decorate_attribute_type(attribute, :enum) do |subtype|
            LiberalEnumType.new(attribute, public_send(attribute.to_s.pluralize), subtype)
          end
        end
      end
    end
    
    # app/types/liberal_enum_type.rb
    class LiberalEnumType < ActiveRecord::Enum::EnumType
      # suppress 
      # returns a value to be able to use +inclusion+ validation
      def assert_valid_value(value)
        value
      end
    end
    

    Usage:

    contact = Contact.new(kind: 'foo')
    contact.valid? #=> false
    contact.errors.full_messages #=> ["Kind is not included in the list"]
    

提交回复
热议问题