Rails自定义验证-只有一条记录可以为真 [英] Rails custom validation - Only one record can be true

查看:67
本文介绍了Rails自定义验证-只有一条记录可以为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个验证,其中只有一条记录是真实的。
我有一个带有活动布尔值列的游戏模型,任何时候都只能活动一个游戏,因此,如果有人尝试在已有活动的情况下创建新的游戏记录,那么他们应该会出现错误。以下是我目前拥有的但无法正常工作!

I'm trying to write a validation where only one record can be true. I have a 'game' model with an 'active' boolean column, only one game can be active at any time, so if someone tries to create a new 'game' record when there is an already active game then they should get an error. Below is what I currently have but isn't working!

validate :active_game

  def active_game
    if active == true && Game.find_by(active: true) == true
       errors[:name] = "a game is already active!"
    end
  end


推荐答案

您还需要检查ID是否已保留记录。否则,再次保存活动游戏将不会成功,因为现有的活动游戏恰好是它本身。

You also need to check against the ID if the record is already persisted. Otherwise, saving the active game again would not succeed because there is an existing active game, which happens to be itself.

validate :only_one_active_game
scope :active, where(:active => true)

protected

def only_one_active_game
  return unless active?

  matches = Game.active
  if persisted?
    matches = matches.where('id != ?', id)
  end
  if matches.exists?
    errors.add(:active, 'cannot have another active game')
  end
end

这篇关于Rails自定义验证-只有一条记录可以为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆