如何在保存新记录之前检查数据库状态

是否有一种更为ruby的惯用方法来处理检查数据库是否有5条记录,然后使用if语句,是否应该在filter或任何类型的validation中完成?

saved_count = Model.where(is_active: true).count if saved_count == MAX_SAVED return {error: 'Cannot save more than 5 records'} end 

只需使用validation:

 class Model # I would create a scope to use it in validation # scope :active, -> { where(is_active: true) } validate :max_count private def max_count errors.add(:base, 'Cannot save more than 5 records') if self.class.active.count == 5 end end