Skip to content

Instantly share code, notes, and snippets.

@vraravam
Created August 7, 2009 10:04
Show Gist options
  • Save vraravam/163818 to your computer and use it in GitHub Desktop.
Save vraravam/163818 to your computer and use it in GitHub Desktop.
validates_existence_of:
This method can be used for both Active records as well as Active Resources - ie anything that responds to 'exists?'. It has been tested to work with Rails v2.2+ and supports all options that validates_each does (like allow_nil, if, unless, etc) and a couple of additional ones (resource_name => the attribute name that might be based on a domain concept; and resource_class => that could be derived from the resource name, but could be namespaced, etc). Here is the code:
def validates_existence_of(*attributes)
options = {:message => 'does not exist'}.merge(attributes.extract_options!)
validates_each(attributes, options) do |record, attr, value|
resource_name = options[:resource_name]
resource_name ||= attr.to_s.gsub(/_id$/, "") if attr.to_s =~ /_id$/
resource_name || attr.to_s # last resort
resource_klass = options[:resource_class] || resource_name.to_s.classify.constantize
attr_value = record.send(attr)
message = "(#{value}) #{options[:message]}"
record.errors.add(attr, message) unless resource_klass.exists?(attr_value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment