Rails put validation in a module mixin?

后端 未结 2 1724
一整个雨季
一整个雨季 2020-12-09 02:43

Some validations are repetitive in my models:

validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
validates :na         


        
相关标签:
2条回答
  • 2020-12-09 03:14
    module Validations
      extend ActiveSupport::Concern
    
      included do
        validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
        validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
      end
    end
    

    The validates macro must be evaluated in the context of the includer, not of the module (like you probably were doing).

    0 讨论(0)
  • 2020-12-09 03:30

    Your module should look something like this:

    module CommonValidations
      extend ActiveSupport::Concern
    
      included do
        validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
        validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
      end
    end
    

    Then in your model:

    class Post < ActiveRecord::Base
      include CommonValidations
    
      ...
    end
    

    I'm using ActiveSupport::Concern here to make the code a little clearer.

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