0

I'm having a problem with an :has_many => :through association which references another :has_many => :through association.

I have a User->Cart->CartItem->Product model setup going in my rails application. Here are the model associations:

class User < ActiveRecord::Base
  has_many :purchases,  :class_name => "Cart",
                        :dependent => :destroy,
                        :conditions => {:purchased => true}
  has_many :items,      :through => :purchases,
                        :readonly => true
  has_many :products,   :through => :purchases,
                        :readonly => true
end

class Cart < Activerecord::Base
  belongs_to :user
  has_many :items,    :class_name => "CartItem",
                      :dependent => :delete_all                 
  has_many :products, :through => :items
end

class CartItem < ActiveRecord::Base
  belongs_to :cart
  belongs_to :product
end

The idea is that a cart has many cart_items, which are just references to existing products. After a cart is marked as purchase, a user should have access to products directly via user.products.

Anyway... I can not figure out how to setup my User model so that the relationship is possible. I keep getting the following error:

Invalid source reflection macro :has_many :through for has_many :products,
:through => :purchases. Use :source to specify the source reflection.

I'm assumming it wants me to add a :source attribute to the has_many :products assoc. in the User model, but that seems silly considering the source association is named identically (and it doesn't work when I add :source => :products anyway).

Does anyone know how I could get this to work? I'd really appreciate any suggestions!

Sorry if this question has been asked before, but I've been searching and I can't find an answer. Thanks in advance.

bschaeffer
  • 2,824
  • 1
  • 29
  • 59
  • possible duplicate of [Ruby-on-Rails: Multiple has_many :through possible?](http://stackoverflow.com/questions/2383479/ruby-on-rails-multiple-has-many-through-possible) – bschaeffer Mar 02 '11 at 21:22

1 Answers1

0

Rails won't allow you chain nested has_many :through associations like that.

There's a similar question here: Ruby-on-Rails: Multiple has_many :through possible?

Community
  • 1
  • 1
dnch
  • 9,565
  • 2
  • 38
  • 41
  • I've set up an instance method that basically does what I wanted it to (based on the post you pointed to). Thanks a ton for link, didn't know this was a problem. – bschaeffer Mar 02 '11 at 21:17
  • 1
    As of rails 3 i believe this is possible – dabobert Dec 13 '15 at 20:48
  • I'm currently upgrading an app from Rails 2.3 (I know) to, eventually, Rails 4.2.5. I'm currently on the Rails 3.0 release and am stuck with this same problem. But yes, I know that in the last 3 release, you can chain has_many :throughs – Kurt Mueller Jan 06 '16 at 13:21