f75893b927
1) Validations Uniqueness should not validate a non-unique document Failure/Error: @obj.errors[:title].should eql(['is already taken']) expected ["is already taken"] got ["translation missing: en.activemodel.errors.models.with_unique_validation.attributes.title.taken"] (compared using eql?) Diff: @@ -1,2 +1,2 @@ -["is already taken"] +["translation missing: en.activemodel.errors.models.with_unique_validation.attributes.title.taken"] # ./spec/couchrest/validations_spec.rb:28:in `block (3 levels) in <top (required)>' Signed-off-by: Marcos Tapajós <tapajos@gmail.com>
44 lines
1.3 KiB
Ruby
44 lines
1.3 KiB
Ruby
# encoding: utf-8
|
|
|
|
module CouchRest
|
|
module Model
|
|
module Validations
|
|
|
|
# Validates if a field is unique
|
|
class UniquenessValidator < ActiveModel::EachValidator
|
|
|
|
# Ensure we have a class available so we can check for a usable view
|
|
# or add one if necessary.
|
|
def setup(klass)
|
|
@klass = klass
|
|
end
|
|
|
|
|
|
def validate_each(document, attribute, value)
|
|
view_name = options[:view].nil? ? "by_#{attribute}" : options[:view]
|
|
# Determine the base of the search
|
|
base = options[:proxy].nil? ? @klass : document.instance_eval(options[:proxy])
|
|
|
|
if base.respond_to?(:has_view?) && !base.has_view?(view_name)
|
|
raise "View #{document.class.name}.#{options[:view]} does not exist!" unless options[:view].nil?
|
|
@klass.view_by attribute
|
|
end
|
|
|
|
docs = base.view(view_name, :key => value, :limit => 2, :include_docs => false)['rows']
|
|
return if docs.empty?
|
|
|
|
unless document.new?
|
|
return if docs.find{|doc| doc['id'] == document.id}
|
|
end
|
|
|
|
if docs.length > 0
|
|
document.errors.add(attribute, :taken, options.merge(:value => value))
|
|
end
|
|
end
|
|
|
|
|
|
end
|
|
|
|
end
|
|
end
|
|
end
|