Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created May 7, 2010 13:23
Show Gist options
  • Save jnunemaker/393411 to your computer and use it in GitHub Desktop.
Save jnunemaker/393411 to your computer and use it in GitHub Desktop.
Validates existence of in MongoMapper
module ValidatesExistenceOfPlugin
def self.included(model)
model.plugin ValidatesExistenceOfPlugin
end
module ClassMethods
def validates_existence_of(*args)
add_validations(args, ValidatesExistenceOfPlugin::ValidatesExistenceOf)
end
end
class ValidatesExistenceOf < Validatable::ValidationBase
def valid?(instance)
instance.send(attribute).present?
end
def message(instance)
super || "does not exist"
end
end
end
MongoMapper::Document.append_inclusions(ValidatesExistenceOfPlugin)
MongoMapper::EmbeddedDocument.append_inclusions(ValidatesExistenceOfPlugin)
@jnunemaker
Copy link
Author

Example usage in combination with belongs_to's:

belongs_to :user
belongs_to :article
validates_existence_of :article
validates_existence_of :user

@jnunemaker
Copy link
Author

This is stupid actually. Just use validates_presence_of. Sometimes one over thinks...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment