2015-09-09 33 views
0

我有一個自定義驗證,它重複了多個模型。有沒有一種方法來重構它並使其乾燥?重構在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 

任何參考鏈接也非常讚賞。謝謝!!

回答

1

嘗試使用顧慮:

應用程序/模型/顧慮/ 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 
0

您可以通過繼承ActiveModel::Validator來輕鬆地製作您自己的自定義驗證器類。在這裏尋找一些簡單的例子:http://api.rubyonrails.org/classes/ActiveModel/Validator.html

+0

我有了這個想法,但customer_segment_id不是我的模型的一個領域。所以我不確定它是否有效。會嗎? –