我在Ruby on Rails3上有一个Object,它在同一个日期不应该存在三次以上。 我在创建时验证对象没有问题,但是当现有对象更新并成为一天中的第四个对象时会发生什么?
我试图在before_save,after_save,after_update之类的情况下挂钩验证等。没有确实有效......
谢谢你们!
这是我目前的验证:
class Dish < ActiveRecord::Base
before_create :creation_validaton
after_save :update_validaton
def creation_validaton
if Dish.find(:all,:conditions => ["date = ?",self.date]).count > 2
errors.add(:date, "more than 3 a day")
return false
else
return true
end
end
def update_validaton
if Dish.find(:all,:conditions => ["date = ?",self.date]).count > 3
errors.add(:date, "more than 3 a day!")
return false
else
return true
end
end
end
答案 0 :(得分:2)
某种这样的。我没有测试它
class CountPerDayValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
count = record.class.where(attribute => value).count
record.errors[attribute] << "more than #{options[:max]} for #{attribute}" if count >= options[:max]
end
end
class Dish < ActiveRecord::Base
validates :date, :count_per_day => {:max => 3}
end