代码之家  ›  专栏  ›  技术社区  ›  Kranthi

在Rails中重构重复的自定义验证

  •  0
  • Kranthi  · 技术社区  · 10 年前

    我有一个自定义验证,它在多个模型中重复。有没有办法重构它并使其干燥?

    class Channel < ActiveRecord::Base
    
      belongs_to :bmc
      has_and_belongs_to_many :customer_segments
    
      validates :name, presence: true
      validate :require_at_least_one_customer_segment
    
      private
    
      def require_at_least_one_customer_segment
        if customer_segments.count == 0
          errors.add_to_base "Please select at least one customer segment"
        end
      end
    
    end
    
    
    
    class CostStructure < ActiveRecord::Base
    
      belongs_to :bmc
      has_and_belongs_to_many :customer_segments
    
      validates :name, presence: true
      validate :require_at_least_one_customer_segment
    
      private
    
      def require_at_least_one_customer_segment
        if customer_segments.count == 0
          errors.add_to_base "Please select at least one customer segment"
        end
      end
    end
    
     class CustomerSegment < ActiveRecord::Base
       has_and_belongs_to_many :channels
       has_and_belongs_to_many :cost_structures
     end
    

    任何参考链接也非常感谢。谢谢!!

    2 回复  |  直到 10 年前
        1
  •  1
  •   madcow    10 年前

    尝试使用关注点:

    app/models/constructures/shared_validations.rb

    module SharedValidations
      extend ActiveSupport::Concern
      include ActiveModel::Validations
    
      included do 
        belongs_to :bmc
        has_and_belongs_to_many :customer_segments
    
        validates :name, presence: true
        validate :require_at_least_one_customer_segment
      end
    end
    

    然后在你的课堂上:

    class CostStructure < ActiveRecord::Base
        include Validateable
    end 
    
        2
  •  0
  •   jeremy.clark    10 年前

    您可以通过继承 ActiveModel::Validator 。请看这里的一些简单示例: http://api.rubyonrails.org/classes/ActiveModel/Validator.html

    推荐文章