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?
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
API:
validates_uniqueness_of :name
Update:
validate do
#uniqueness code
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With