Skip to content

Instantly share code, notes, and snippets.

@bkimble
Created November 7, 2011 22:35
Show Gist options
  • Save bkimble/1346429 to your computer and use it in GitHub Desktop.
Save bkimble/1346429 to your computer and use it in GitHub Desktop.
Association Helper Methods with .fields for MongoMapper
# Module to allow us to query listings and get back a Plucky object so we can
# continue to form the query before firing it off to mongo. Include this in
# any model that has many :listings. This is to get around MongoMapper
# not allowing us to use methods on the association helper methods it adds to
# the classes. Billy Kimble 2011-05-01
module ListingsFinder
FIELDSETS = {
'homepage' => ["id","title","description"]
}
def listings_finder(fieldset=nil)
# what is our ID array? Assume the assocation is always :listings
key = self.class.associations[:listings].options[:in]
query = Listing.where(:_id => self.send(key))
if fieldset && set = FIELDSETS[fieldset]
query.fields(set)
else
query
end
end
end
class Store
include MongoMapper::Document
key :listing_ids, Array
many :listings, :in => :listing_ids
include ListingsFinder
end
@listings = Store.first.listings_finder('homepage').limit(4).all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment