rap*_*tle 20 ruby validation activerecord ruby-on-rails ruby-on-rails-4
我正在尝试编写一个验证,其中只有一条记录可以为真.我有一个带有'主动'布尔列的"游戏"模型,任何时候只有一个游戏可以激活,所以如果有人试图在已经有效的游戏中创建一个新的"游戏"记录,那么他们应该会收到错误.以下是我目前所拥有但不起作用的内容!
validate :active_game
def active_game
if active == true && Game.find_by(active: true) == true
errors[:name] = "a game is already active!"
end
end
Run Code Online (Sandbox Code Playgroud)
onu*_*kan 56
我认为你可以检查active_game的唯一性.
validates_uniqueness_of :active_game, if: :active_game
kri*_*lim 10
如果记录已经保留,您还需要检查ID.否则,再次保存活动游戏将不会成功,因为存在一个现有的活动游戏,这恰好本身.
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8460 次 |
最近记录: |