lib/mongoid/validations/presence.rb in mongoid-2.8.1 vs lib/mongoid/validations/presence.rb in mongoid-3.0.0.rc
- old
+ new
@@ -1,8 +1,8 @@
# encoding: utf-8
-module Mongoid #:nodoc:
- module Validations #:nodoc:
+module Mongoid
+ module Validations
# Validates that the specified attributes are not blank (as defined by
# Object#blank?).
#
# @example Define the presence validator.
@@ -26,19 +26,45 @@
#
# @since 2.4.0
def validate_each(document, attribute, value)
field = document.fields[attribute.to_s]
if field.try(:localized?) && !value.blank?
- value.each_pair do |locale, value|
- document.errors.add(attribute, :blank_on_locale, options.merge(:location => locale)) if value.blank?
+ value.each_pair do |_locale, _value|
+ document.errors.add(
+ attribute,
+ :blank_in_locale,
+ options.merge(location: _locale)
+ ) if _value.blank?
end
elsif document.relations.has_key?(attribute.to_s)
- if value.blank? && document.send(attribute).blank?
+ if relation_or_fk_missing?(document, attribute, value)
document.errors.add(attribute, :blank, options)
end
else
document.errors.add(attribute, :blank, options) if value.blank?
end
+ end
+
+ private
+
+ # Returns true if the relation is blank or the foreign key is blank.
+ #
+ # @api private
+ #
+ # @example Check is the relation or fk is blank.
+ # validator.relation_or_fk_mising(doc, :name, "")
+ #
+ # @param [ Document ] doc The document.
+ # @param [ Symbol ] attr The attribute.
+ # @param [ Object ] value The value.
+ #
+ # @return [ true, false ] If the doc is missing.
+ #
+ # @since 3.0.0
+ def relation_or_fk_missing?(doc, attr, value)
+ return true if value.blank? && doc.send(attr).blank?
+ metadata = doc.relations[attr.to_s]
+ metadata.stores_foreign_key? && doc.send(metadata.foreign_key).blank?
end
end
end
end