我是否需要在每个验证器中进行重复的对象检查?

时间:2013-09-17 13:41:17

标签: ruby-on-rails ruby validation refactoring

当我if shift

时,我是否真的需要在我的自定义验证器中查看validates :shift, presence: true

我可以以某种方式重构它吗?

class ShiftLog < ActiveRecord::Base
  belongs_to :shift
  validates :shift, presence: true
  validate  :check_limit

  def check_limit
    if shift
      shift_logs = ShiftLog.by_shift(shift)
      if shift_logs.count >= self.shift.limit
        errors.add(:shift_id, "Exceeded limit")
      end
    end
  end
end

2 个答案:

答案 0 :(得分:0)

是的,您不需要再次检查。它看起来不错,除了你可以写一个班轮条件:

 def check_limit
   shift_logs = ShiftLog.by_shift(shift)
   errors.add(:shift_id, "Exceeded limit")  if shift_logs.count >= self.shift.limit
 end

答案 1 :(得分:0)

你需要它,所以当没有分配班次时它不会粉碎。你有另一个验证的事实并没有改变这个事实,它可能会失败。