我正在尝试创建一个系统,我的站点的用户可以在其中收藏页面。这些页面有两种类型,俱乐部或体育。所以,我有四个模型,关联如下:
用户模型:
class User < ActiveRecord::Base
..
has_many :favorites
has_many :sports, :through => :favorites
has_many :clubs, :through => :favorites
..
end
收藏模型:
class Favorite < ActiveRecord::Base
..
belongs_to :user
belongs_to :favoritable, :polymorphic => true
end
俱乐部型号:
class Club < ActiveRecord::Base
..
has_many :favorites, :as => :favoritable
has_many :users, :through => :favorites
def to_param
slug
end
end
运动模型:
class Sport < ActiveRecord::Base
..
def to_param
slug
end
..
has_many :favorites, :as => :favoritable
has_many :users, :through => :favorites
..
end
本质上,用户通过收藏夹拥有_许多运动或俱乐部,并且收藏夹、运动和俱乐部之间的关联是多态的。
在实践中,这一切都按照我想要的方式工作,我设计的整个系统都在工作。但是,我在我的网站上使用 Rails_Admin,在三个地方出现错误:
这是
/admin/user
上的错误消息(gist) .所有错误都相似,引用 ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to source_reflection.foreign_key, but source_reflection is nil:
.谁能指出我正确的方向,以便我可以解决这个问题?我到处搜索,并询问其他程序员/专业人员,但没有人能发现我的模型中的错误。非常感谢!
最佳答案
好吧,好吧,我终于解决了这个问题,并认为我会发布修复程序,以防将来它可以帮助其他人(没有人喜欢找到有同样问题的其他人并且没有发布答案)。
事实证明,带有多态 has_many :through
,需要更多的配置。我的用户模型应该是这样的:
class User < ActiveRecord::Base
..
has_many :favorites
has_many :sports, :through => :favorites, :source => :favoritable, :source_type => "Sport"
has_many :clubs, :through => :favorites, :source => :favoritable, :source_type => "Club"
..
end
This answer另一个关于多态的问题
has_many :through
协会帮助我解决了这个问题。
关于ruby-on-rails - has_many :through 的源反射错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16677703/