Skip to content

Instantly share code, notes, and snippets.

@jmaicher
Created November 30, 2010 10:42
Show Gist options
  • Save jmaicher/721500 to your computer and use it in GitHub Desktop.
Save jmaicher/721500 to your computer and use it in GitHub Desktop.
Problem using any_of criteria with :all
def self.find_by_string (query)
users = User.any_of({ :username => /^#{Regexp.escape(query)}/ }, { :name => /#{Regexp.escape(query)}/ }).first
end
# returns #<User _id: 4cf4d4594dd96225fe00002d, deleted_at: nil, created_at: 2010-11-30 10:39:21 UTC, updated_at: 2010-11-30 10:39:21 UTC, name: "John Doe", username: "johndoe_44" [..] >
def self.find_by_string (query)
users = User.any_of({ :username => /^#{Regexp.escape(query)}/ }, { :name => /#{Regexp.escape(query)}/ }).all
end
# returns #<Mongoid::Criteria:0x3e1c2d0 @selector={:deleted_at=>{"$exists"=>false}, "$or"=>[{:username=>/^johndoe_44/}, {:name=>/johndoe_44/}]}, @options={}, @klass=User, @documents=[]>
# my fault - the enumeration doesn't show matching documents with inspect
def self.find_by_string (query)
users = User.any_of({ :username => /^#{Regexp.escape(query)}/ }, { :name => /#{Regexp.escape(query)}/ }).all
end
users = User.find_by_string "string"
users.each do |user|
# do sth
end
# any_of again: criteria needs a "kicker". it works fine with .to_a
def self.find_by_string (query)
users = User.any_of({ :username => /^#{Regexp.escape(query)}/ }, { :name => /#{Regexp.escape(query)}/ }).to_a
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment