2016-01-24 32 views
3

如果数据库有5条记录,而不是使用if语句,是否应该在过滤器或任何类型的验证中完成,是否还有更多ruby惯用方法来处理检查?如何在保存新记录之前检查数据库状态

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

回答

5

只需使用验证:

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 
+0

你可能不想 “上:打造” 使用。如果有5个活动和1个非活动并且非活动更新为活动? –

+0

@BjörnNilsson绝对正确,谢谢,编辑! –

+0

所以我有类似validates:name,presence:true,[我不能追加:max_count到这个] – eugenekgn

相关问题