无法验证无表格类的唯一性

时间:2012-12-15 12:19:42

标签: ruby-on-rails ruby ruby-on-rails-3 validation

我有以下代码:

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>'

这似乎有点奇怪。关于可能出错的任何想法?

2 个答案:

答案 0 :(得分:5)

您可以利用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

的子类的每个生活对象

答案 1 :(得分:1)

API:

validates_uniqueness_of :name

更新

validate do
  #uniqueness code
end