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...


On Apr 1, 5:05 am, Fernando Perez <[email protected]>
wrote:
> I think the problem lies in the ability for the DB to perform a join
> across multiple tables which in fact breaks encapsulation!
>
> Maybe I should break down my DB query that uses joins into smaller
> queries. The code is obviously less efficient, but it's more
> maintainable, as each model is only concerned with its own stuff, and
> therefore I don't have to make edits across various models just because
> I changed the name or type of attributes in a single model.
>
> Using joins across multiple models doesn't feel right anymore.
> --
> Posted viahttp://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to