简体   繁体   English

Rails - 是否有可能找到违反唯一验证的记录

[英]Rails - is it possible to find the record that violates unique validation

Considering following as an example以下面为例

class SuperHero < ActiveRecord::Base
  validates :weapon, uniqueness: true
end

So when I create所以当我创建

SuperHero.create!(name: "Thor", weapon: "hammer")
SuperHero.create!(name: "Spiderman", weapon: "hammer") => Weapon has already been taken

Is it possible to add, the error message Weapon has already been taken by Thor using the default unique validation?是否可以添加错误消息Weapon has already been taken by Thor using the default unique validation? So that the user can easily find the whom currently the weapon is assigned to?以便用户可以轻松找到当前武器分配给谁?

You will need to implement your own validation.您将需要实施自己的验证。 Something like this:像这样:

class SuperHero < ActiveRecord::Base
  validates :weapon, uniqueness: true

  before_validation -> {
    existing_super_hero = SuperHero.find_by_weapon self.weapon

    if existing_super_hero && existing_super_hero.id != self.id
      self.errors.add(:base, "Weapon has already been taken by #{existing_super_hero.name}")
      throw :abort
    end
  }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM