如何通过更新验证来限制具有相同属性的对象数量?

时间:2011-08-14 17:35:18

标签: ruby-on-rails ruby-on-rails-3 activerecord

我在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

1 个答案:

答案 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