【问题标题】:Rails - "Invalid source reflection" for :has_many => :throughRails - :has_many => :through 的“无效源反射”
【发布时间】: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 =&gt; :products 时它不起作用)。

有谁知道我怎样才能让它工作?我真的很感激任何建议!

很抱歉,如果以前有人问过这个问题,但我一直在搜索,但找不到答案。提前致谢。

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:

Rails 不允许您像这样链接嵌套的 has_many :through 关联。

这里有一个类似的问题:Ruby-on-Rails: Multiple has_many :through possible?

【讨论】:

  • 我已经设置了一个实例方法,它基本上可以满足我的要求(基于您指向的帖子)。非常感谢链接,不知道这是个问题。
  • 从 Rails 3 开始,我相信这是可能的
  • 我目前正在将一个应用程序从 Rails 2.3(我知道)升级到 Rails 4.2.5。我目前正在使用 Rails 3.0 版本,并且遇到了同样的问题。但是,是的,我知道在最后 3 个版本中,您可以链接 has_many :throughs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 2014-09-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多