2010-06-03 20:20:53 +00:00
|
|
|
require 'mongoid'
|
|
|
|
|
2010-04-25 00:33:38 +00:00
|
|
|
## various patches
|
|
|
|
module Mongoid #:nodoc:
|
2010-05-09 12:44:53 +00:00
|
|
|
|
|
|
|
# Enabling scope in validates_uniqueness_of validation
|
2010-04-25 00:33:38 +00:00
|
|
|
module Validations #:nodoc:
|
|
|
|
class UniquenessValidator < ActiveModel::EachValidator
|
2010-05-10 22:39:52 +00:00
|
|
|
def validate_each(document, attribute, value)
|
|
|
|
conditions = { attribute => value, :_id.ne => document._id }
|
|
|
|
|
|
|
|
if options.has_key?(:scope) && !options[:scope].nil?
|
|
|
|
[*options[:scope]].each do |scoped_attr|
|
|
|
|
conditions[scoped_attr] = document.attributes[scoped_attr]
|
|
|
|
end
|
|
|
|
end
|
2010-05-24 00:18:23 +00:00
|
|
|
|
2010-06-02 00:39:05 +00:00
|
|
|
# Rails.logger.debug "conditions = #{conditions.inspect} / #{options[:scope].inspect}"
|
2010-05-10 22:39:52 +00:00
|
|
|
|
|
|
|
return if document.class.where(conditions).empty?
|
2010-05-24 00:18:23 +00:00
|
|
|
|
2010-05-10 22:39:52 +00:00
|
|
|
# if document.new_record? || key_changed?(document)
|
|
|
|
document.errors.add(attribute, :taken, :default => options[:message], :value => value)
|
|
|
|
# end
|
2010-04-25 00:33:38 +00:00
|
|
|
end
|
2010-05-10 22:39:52 +00:00
|
|
|
|
|
|
|
# protected
|
|
|
|
# def key_changed?(document)
|
|
|
|
# (document.primary_key || {}).each do |key|
|
|
|
|
# return true if document.send("#{key}_changed?")
|
|
|
|
# end; false
|
|
|
|
# end
|
2010-04-25 00:33:38 +00:00
|
|
|
end
|
|
|
|
end
|
2010-05-09 12:44:53 +00:00
|
|
|
|
|
|
|
# FIX BUG #71 http://github.com/durran/mongoid/commit/47a97094b32448aa09965c854a24c78803c7f42e
|
|
|
|
module Associations
|
|
|
|
module InstanceMethods
|
|
|
|
def update_embedded(name)
|
|
|
|
association = send(name)
|
|
|
|
association.to_a.each { |doc| doc.save if doc.changed? || doc.new_record? } unless association.blank?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|