2010-06-23 11:58:35 +02:00
|
|
|
# encoding: utf-8
|
2010-06-21 21:33:46 +02:00
|
|
|
|
|
|
|
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.
|
2011-02-09 21:21:03 +01:00
|
|
|
def setup(model)
|
|
|
|
@model = model
|
2010-06-21 21:33:46 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def validate_each(document, attribute, value)
|
2010-06-21 23:12:15 +02:00
|
|
|
view_name = options[:view].nil? ? "by_#{attribute}" : options[:view]
|
2011-02-09 21:21:03 +01:00
|
|
|
model = document.model_proxy || @model
|
2010-06-22 14:15:30 +02:00
|
|
|
# Determine the base of the search
|
2011-02-09 21:21:03 +01:00
|
|
|
base = options[:proxy].nil? ? model : document.instance_eval(options[:proxy])
|
2010-06-21 23:12:15 +02:00
|
|
|
|
2010-06-22 14:15:30 +02:00
|
|
|
if base.respond_to?(:has_view?) && !base.has_view?(view_name)
|
2010-06-21 23:12:15 +02:00
|
|
|
raise "View #{document.class.name}.#{options[:view]} does not exist!" unless options[:view].nil?
|
2011-02-09 21:21:03 +01:00
|
|
|
model.view_by attribute
|
2010-06-21 21:33:46 +02:00
|
|
|
end
|
|
|
|
|
2010-06-21 23:12:15 +02:00
|
|
|
docs = base.view(view_name, :key => value, :limit => 2, :include_docs => false)['rows']
|
2010-06-21 21:33:46 +02:00
|
|
|
return if docs.empty?
|
|
|
|
|
|
|
|
unless document.new?
|
|
|
|
return if docs.find{|doc| doc['id'] == document.id}
|
|
|
|
end
|
|
|
|
|
|
|
|
if docs.length > 0
|
2011-02-21 11:27:35 +01:00
|
|
|
document.errors.add(attribute, :taken, options.merge(:value => value))
|
2010-06-21 21:33:46 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|