Has_many :through 2 models

Let’s say I have the following models:

User
has_many :orders
has_many :items, :through => :orders

Order
belongs_to :user
has_many :items
has_many :products, :through => :items

Item
belongs_to :order
belongs_to :product

Product
has_many :items
has_many :orders, :through => items

Is it possible to do:
@user = User.find(1)
@products = @user.products

I have tried but it ddin’t work. If it is impossible to do, what would
be the solution to that?

If all you need to do is get a list of all products ordered by a given
user, you could write the following method

class User << ActiveRecord::Base

def products
Product.find :all, :include => [:items], :conditions =>
[“items.user_id = ? and products.id = items.product_id”, self.id]
end

end

Best,

kb

On Apr 26, 5:26 pm, Fernando P. [email protected]
wrote:

Let’s say I have the following models:

User
has_many :orders

On Apr 26, 5:26 pm, Fernando P. [email protected]

Therefore this means that :through can only work through one model.

Thank you Kyle for your tip.

On Apr 26, 5:26 pm, Fernando P. [email protected]
wrote:

Let’s say I have the following models:
(…)
Is it possible to do:
@user = User.find(1)
@products = @user.products

I have tried but it ddin’t work. If it is impossible to do, what would
be the solution to that?

Try this:

http://code.torchbox.com/svn/rails/plugins/nested_has_many_through/

See the README for more info.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs