我有一個自定義驗證,它重複了多個模型。有沒有一種方法來重構它並使其乾燥?重構在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
任何參考鏈接也非常讚賞。謝謝!!
我有了這個想法,但customer_segment_id不是我的模型的一個領域。所以我不確定它是否有效。會嗎? –