当我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
答案 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)
你需要它,所以当没有分配班次时它不会粉碎。你有另一个验证的事实并没有改变这个事实,它可能会失败。