ruby on rails - How to check for a database state before saving new records -


is there more ruby idiomatic way handle checking if database has 5 records other use if statement, should done in filter or type of validation?

saved_count = model.where(is_active: true).count if saved_count == max_saved   return {error: 'cannot save more 5 records'} end 

just use validation:

class model   # create scope use in validation   # scope :active, -> { where(is_active: true) }    validate :max_count    private    def max_count     errors.add(:base, 'cannot save more 5 records') if self.class.active.count == 5   end end 

Comments