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

Refactoring repeated custom validation in Rails

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

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

任何参考 link 也很多 appreciated.Thanks!!

您可以通过继承 ActiveModel::Validator 轻松创建自己的自定义验证器 class。在这里寻找一些简单的例子:http://api.rubyonrails.org/classes/ActiveModel/Validator.html

尝试使用关注点:

app/models/concerns/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