Skip to content

Instantly share code, notes, and snippets.

@olivoil
Created March 15, 2011 16:18
Show Gist options
  • Save olivoil/870961 to your computer and use it in GitHub Desktop.
Save olivoil/870961 to your computer and use it in GitHub Desktop.
Example model to persist Mongoid::Criteria as Searches
class Search
include Mongoid::Document
field :query, :type => Hash
field :collection
embedded_in :user
def to_criteria
Mongoid::Criteria.new( collection.titleize.constantize ).fuse( query )
end
end
# Then you can store a criteria like this :
criteria = Product.where(:name => /Honda/, 'properties.color' => 'blue')
user.searches << Search.new(:query => criteria.scoped, :collection => criteria.klass.to_s)
# And retrieve it to use it later
search = user.searches.first.to_criteria
search.limit(10).to_a #=> array of 10 products matching your search
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment