Skip to content

Instantly share code, notes, and snippets.

@jmaicher
Created December 4, 2010 12:36
Show Gist options
  • Save jmaicher/728152 to your computer and use it in GitHub Desktop.
Save jmaicher/728152 to your computer and use it in GitHub Desktop.
Mongoid doesn't automatically cast strings to BSON::ObjectID
# this doesn't work, because username_or_id is a string either way
def self.find_by_username_or_id(username_or_id)
User.any_of({:username => username_or_id}, {:_id => username_or_id}).first
# raises "illegal ObjectID format" exception
end
# this works because we cast valid object ids to BSON::ObjectID
def self.find_by_username_or_id(username_or_id)
if BSON::ObjectID.legal?(username_or_id)
User.first :conditions => {:_id => BSON::ObjectID(username_or_id)}
else
User.first :conditions => {:username => username_or_id}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment