Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot validate uniqueness in tableless class

I have the following code:

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

  attr_accessor :name
  validates :name, uniqueness: true
end

however, when testing the uniqueness validation I receive:

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

This seems somewhat odd. Any ideas as to what might be wrong?

like image 598
Neil Middleton Avatar asked Feb 19 '23 04:02

Neil Middleton


2 Answers

You can leverage ruby's object space to do the following:

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

This basically walks over every living object that matches (or is a subclass of) Foo

like image 144
krichard Avatar answered Feb 26 '23 21:02

krichard


API:

validates_uniqueness_of :name

Update:

validate do
  #uniqueness code
end
like image 45
Valery Kvon Avatar answered Feb 26 '23 22:02

Valery Kvon