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

时间:2016-01-24 15:53:16

标签: ruby-on-rails ruby ruby-on-rails-4

是否有更多的ruby惯用方法来处理检查数据库是否有5条记录,然后使用if语句,是否应该在过滤器或任何类型的验证中完成?

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

1 个答案:

答案 0 :(得分:5)

只需使用验证:

// extends byte[] to create SHA256 hash code with seed and salt of supplied size
public static byte[] GetSHA256HashCode(this byte[] value, byte[] seed, int prefix = 0)
{
    var salt = new byte[prefix];
    RNG.GetBytes(salt);
    return salt.Concat(seed.Concat(salt).Concat(value).ToArray().GetSHA256HashCode()).ToArray();
}

// extends byte[] to compare SHA256 hash code with seed and salt of supplied size to supplied hash code
public static bool IsEqualToSHA256HashCode(this byte[] value, byte[] code, byte[] seed, int prefix = 0)
{
    return seed.Concat(code.Take(prefix)).Concat(value).ToArray().GetSHA256HashCode().SequenceEqual(code.Skip(prefix));
}