eug*_*kgn 3 ruby ruby-on-rails ruby-on-rails-4
是否有一种更为红宝石的惯用方法来处理检查数据库是否有5条记录,然后使用if语句,是否应该在过滤器或任何类型的验证中完成?
saved_count = Model.where(is_active: true).count
if saved_count == MAX_SAVED
return {error: 'Cannot save more than 5 records'}
end
Run Code Online (Sandbox Code Playgroud)
只需使用验证:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |