【发布时间】:2011-07-06 05:49:57
【问题描述】:
我在引用另一个 :has_many => :through 关联的 :has_many => :through 关联时遇到问题。
我的 rails 应用程序中有一个 User->Cart->CartItem->Product 模型设置。以下是模型关联:
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
这个想法是,一个购物车有许多 cart_items,它们只是对现有产品的引用。将购物车标记为购买后,用户应该可以直接通过user.products 访问产品。
无论如何...我不知道如何设置我的User 模型,以便建立关系。我不断收到以下错误:
Invalid source reflection macro :has_many :through for has_many :products,
:through => :purchases. Use :source to specify the source reflection.
我假设它希望我将:source 属性添加到has_many :products assoc。在 User 模型中,但考虑到源关联的名称相同,这似乎很愚蠢(无论如何,当我添加 :source => :products 时它不起作用)。
有谁知道我怎样才能让它工作?我真的很感激任何建议!
很抱歉,如果以前有人问过这个问题,但我一直在搜索,但找不到答案。提前致谢。
【问题讨论】:
标签: ruby-on-rails activerecord