gpt4 book ai didi

ruby-on-rails - 无法验证无表类中的唯一性

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:07 25 4
gpt4 key购买 nike

我有以下代码:

class Foo
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming

attr_accessor :name
validates :name, uniqueness: true
end

但是,在测试我收到的唯一性验证时:

/Users/neil/.rvm/gems/ruby-1.9.3-p286@config-keeper/gems/activemodel-3.2.9/lib/active_model/validations/validates.rb:96:in `rescue in block in validates': Unknown validator: 'UniquenessValidator' (ArgumentError)
from /Users/neil/.rvm/gems/ruby-1.9.3-p286@config-keeper/gems/activemodel-3.2.9/lib/active_model/validations/validates.rb:93:in `block in validates'
from /Users/neil/.rvm/gems/ruby-1.9.3-p286@config-keeper/gems/activemodel-3.2.9/lib/active_model/validations/validates.rb:90:in `each'
from /Users/neil/.rvm/gems/ruby-1.9.3-p286@config-keeper/gems/activemodel-3.2.9/lib/active_model/validations/validates.rb:90:in `validates'
from /Users/neil/code/open_source/config_keeper/app/models/foo.rb:8:in `<class:App>'

这似乎有点奇怪。关于可能出现的问题有什么想法吗?

最佳答案

您可以利用 ruby​​ 的对象空间来执行以下操作:

class Foo
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming

attr_accessor :name
validate do
if self.name && ObjectSpace.each_object(self.class).select{|o| o.name == self.name }.size > 1
errors.add(:name,"not unique")
end
end
end

a = Foo.new
b = Foo.new
a.valid? #=> true because of if self.name
a.name = "bar"
a.valid? #=> true because of .size > 1
b.name = "bar"
a.valid? #=> false
b.valid? #=> false

这基本上遍历了匹配Foo的每个 living 对象(或者是 Foo 的子类)

关于ruby-on-rails - 无法验证无表类中的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13892107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com