Rails仅在加载时验证关联

时间:2011-07-06 14:12:17

标签: ruby-on-rails validation model associations

我有一个活动模型,其中有很多参与者,我希望确保参与者在更新活动及其参与者时始终存在。我的活动模型中有以下方法可以解决这个问题:

def must_have_participant
  if self.participants.size == 0 || self.participants.size == self.participants.to_ary.find_all{ |p| p.marked_for_destruction? }.count
    self.errors[:base] << I18n.t(:msg_activity_must_have_participant)
  end
end

问题是参与者是懒惰的,如果我只是自己更新活动,我想避免。我尝试了以下替代方案,但是,已加载?使用:_destroy标志删除所有参与者时返回false。

def must_have_participant
  if self.new_record? || self.participants.loaded?
    if self.participants.size == 0 || self.participants.size == self.participants.to_ary.find_all{ |p| p.marked_for_destruction? }.count
      self.errors[:base] << I18n.t(:msg_activity_must_have_participant)
    end
  end
end

是否有替代加载?我可以用来知道参与者是否会更新?

2 个答案:

答案 0 :(得分:0)

我在最近创建的验证中做了类似的事情。我搜索了原始记录,并根据新值检查了原始值。不保证我的代码适合您,但这是我的应用程序代码:

    orig_rec = self.find(id)
    if participant_ids.size != orig_rec.participant_ids.size

请注意,我检查了participant_ids的大小,而不是获取所有参与者记录并检查它们的大小。这应该更有效率。

我不知道在ruby中是否存在某种内置函数来执行此操作,我很想知道哪些特定于rails特定的人可能会建议。

答案 1 :(得分:0)

作为参考,我修改过这样的方法:

def must_have_participant
  if self.new_record? || self.association(:participants).loaded?
    if self.participants.size == 0 || self.participants.size == self.participants.select{ |p| p.marked_for_destruction? }.size
      self.errors[:base] << I18n.t(:msg_must_have_participant)
    end
  end
end