Ruby on rails 一次验证多个模型或如何正确进行验证

Ruby on rails 一次验证多个模型或如何正确进行验证,ruby-on-rails,ruby,ruby-on-rails-3.1,Ruby On Rails,Ruby,Ruby On Rails 3.1,我有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 :netw

我有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
类AttachNetworkToUsertrue 属于:网络 属于:用户 验证:是否附加句号? def period_attach? user=AttachNetworkToUser。选择(“id,dt_begin,dt_end”)。其中(“network_id=:network_id”,{:network_id=>self.network_id}) user.each do|t| if((self.dt_begin>=t.dt_begin和self.dt_begin=t.dt_begin和self.dt_end t.dt_end) self.errors[:dt_begin]self.dt_end self.errors[:dt\u begin]self,:user\u id=>self.user\u id,:network\u id=>self.network\u id,:dt\u begin=>self.dt\u begin,:user\u id=>self.user\u id}

如何正确解决这一目标。
可能将验证代码放在其他类中并发送如下参数:
AttachModelValidator.new({:Attach=>self,:user\u id=>self.user\u id,:network\u id=>self.network\u id,:dt\u begin=>self.dt\u begin,:user\u id=>self.user\u id}).valid

通常,我会说在每个模型中保留所有验证,以便代码被很好地理解

从技术上讲,可以做到这一点:

如果您的字段在不同的模型中具有相同的名称,那么您可以在一个模块中一次性写入所有验证,并将您的模型放在同一个模块下

如果字段名称不同,可以在共享模块中定义一个方法,以接收字段名称并执行验证

同样,我不建议这样做,除非你有一个共同的逻辑,你想在模型之间共享

干杯