如何在保存新记录之前检查数据库状态 [英] How to check for a database state before saving new records
本文介绍了如何在保存新记录之前检查数据库状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更 ruby 惯用的方法来处理检查数据库是否有 5 条记录,而不是使用 if 语句,这应该在过滤器或任何类型的验证中完成吗?
Is there a more ruby idiomatic way to handle checking if database has 5 records other then to use an if statement, should this be done in a filter or any type of validation?
saved_count = Model.where(is_active: true).count
if saved_count == MAX_SAVED
return {error: 'Cannot save more than 5 records'}
end
推荐答案
只需使用验证:
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
这篇关于如何在保存新记录之前检查数据库状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文