我有 7 个模型附加,为其他模型设置了附加日期。我需要验证随员的日期没有交叉点,例如:
class AttachNetworkToUser < ActiveRecord::Base
attr_accessible :dt_begin, :dt_end, :network_id, :user_id
validates :dt_begin, :dt_end, :network_id, :user_id, :presence => true
belongs_to :network
belongs_to :user
validate :period_attach?
def period_attach?
user = AttachNetworkToUser.select("id, dt_begin, dt_end").where("network_id = :network_id " , { :network_id => self.network_id} )
user.each do |t|
if ( (self.dt_begin >= t.dt_begin and self.dt_begin <= t.dt_end) or (self.dt_end >= t.dt_begin and self.dt_end <= t.dt_end) ) or (self.dt_begin < t.dt_begin and self.dt_end > t.dt_end )
self.errors[:dt_begin] << " intersection periud! You can consolidate with " + (t.dt_end+1).to_s
end
if self.dt_begin > self.dt_end
self.errors[:dt_begin] << " can not be more dt_end"
end
end
end
end
它看起来像代码气味。在其他 Attache 模型中,我重复了此验证的代码,但其他参数如下:{:Attach=>self,:user_id=>self.user_id,:network_id=>self.network_id,:dt_begin=>self.dt_begin,:user_id=>self.user_id}
如何正确解决这个目标。也许将验证代码放在其他类中并像这样发送参数:AttachModelValidator.new({:Attach=>self,:user_id=>self.user_id,:network_id=>self.network_id,:dt_begin=>self.dt_begin,:user_id=>self.user_id}).valid