I'm using Rails 3.2 and Mongoid and I need to set up a simple purchases association. Current I have:
class Item
has_many :purchases
class Buyer
has_many :purchases
class Purchase
has_one :buyer
has_one :item
I'd like to be able to call all the items purchased by a given buyer which I current achieve with: def purchased_by(buyer_id) items = [] ids = Buyer.find(buyer_id).purchase_ids Item.each do |i| items << i if (i.purchase_ids & ids).length > 0 end items end
But this seems horribly inefficient. Any thoughts?
Try this:
class Buyer
def items_purchased
purchases.collect(&:item)
end
end
Then given an object buyer
, you can get what you want by calling:
buyer.items_purchased