Validate presence of polymorphic parent

后端 未结 5 916
耶瑟儿~
耶瑟儿~ 2021-02-19 09:49

I am developing a Rails 3.2 application with the following models:

class User < ActiveRecord::Base
  # Associations
  belongs_to :authenticatable, polymorphic         


        
5条回答
  •  梦谈多话
    2021-02-19 10:01

    You can just move validation to before_save callback and it will work fine:

    class User < ActiveRecord::Base
      # Associations
      belongs_to :authenticatable, polymorphic: true
    
      # Validations
      before_save :check_authenticatable
    
      def check_authenticatable
        unless authenticatable
          errors[:customizable] << "can't be blank"
          false
        end
      end
    end
    

提交回复
热议问题