OOP road block

I think this is a common 'dilemma' that comes across every now and then. "Which model should I ask for this information"? I also think there's no right answer. But here's my two cents:

In your case, you want to know which a product was purchased by a user, so the question could go both ways: Did a user purchase this product, or was this product purchased by the user. I think it depends on your views and controllers, in other words, what is the main object you find out the relationship about? If you're on a user view and want to list purchased products, you might just ask @user.orders.each { |o| o.products }.flatten (or some such thing). Similarly, @product.orders.each { |o| o.user }.flatten would give you all users who purchased that product. (this is all making some assumptions about your relationships).

In either case, you are working with either an instance of User, or an instance of Product, so I think that that this should not be a class method, but an instance method.

Same goes when you're already dealing with a user instance and a product instance and you want to find out if that relationship exists, which is more to the point of your original post. How about an instance method on the User class called has_purchased?:

@user.has_purchased?(@product) => true #or false

Here's a stab at that method... #class User < AR:Base def has_purchased?(product)   !self.orders.products.find_by_id(product).nil? end

About joins, I think they are absolutely needed. Some models are more "self contained" than others, but since you're working with a relational model, it is natural that some models depend on others, and using :joins or :include in your finders makes life easier in many cases...

It also depends how optimal your SQL ends up.

Blog: http://random8.zenunit.com/ Learn rails: http://sensei.zenunit.com/