Created
December 4, 2010 12:36
-
-
Save jmaicher/728152 to your computer and use it in GitHub Desktop.
Mongoid doesn't automatically cast strings to BSON::ObjectID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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