has_many的源反射错误:通过

Ale*_*cia 4 model ruby-on-rails polymorphic-associations model-associations rails-admin

我正在尝试创建一个系统,我的网站的用户可以在其中收藏页面.这些页面有两种类型,俱乐部或体育.所以,我有四个模型,相关联:

用户模型:

class User < ActiveRecord::Base
    ..
    has_many :favorites
    has_many :sports,    :through => :favorites
    has_many :clubs,     :through => :favorites
    ..
end
Run Code Online (Sandbox Code Playgroud)

收藏夹型号:

class Favorite < ActiveRecord::Base
    ..

    belongs_to :user
    belongs_to :favoritable, :polymorphic => true

end
Run Code Online (Sandbox Code Playgroud)

俱乐部型号:

class Club < ActiveRecord::Base
    ..

    has_many :favorites, :as => :favoritable
    has_many :users, :through => :favorites

    def to_param
      slug
    end
end
Run Code Online (Sandbox Code Playgroud)

运动模特:

class Sport < ActiveRecord::Base
    ..

    def to_param
        slug
    end

    ..

    has_many :favorites,   :as => :favoritable
    has_many :users,       :through => :favorites

    ..
end
Run Code Online (Sandbox Code Playgroud)

从本质上讲,用户可以通过收藏夹进行体育或俱乐部,而收藏,体育和俱乐部之间的关联是多态的.

在实践中,这一切都完全按照我想要的方式工作,并且我设计的整个系统都有效.但是,我在我的网站上使用Rails_Admin,我在三个地方出错:

  1. 第一次加载仪表板(/ admin)时.如果我刷新页面,它工作正常.
  2. 在Rails_Admin中加载用户模型时
  3. 在Rails_Admin中加载收藏夹模型时

这是/admin/user (gist)上的错误消息.所有错误都是相似的,参考ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to source_reflection.foreign_key, but source_reflection is nil:.

任何人都可以指出我正确的方向,以便我可以解决这个问题吗?我一直在搜索,并询问其他程序员/专业人士,但没有人能在我的模型中发现错误.非常感谢!

Ale*_*cia 12

好吧,好吧,我终于解决了这个问题,并认为我会发布这个修复程序以防万一它将来帮助其他人(没有人喜欢找到有同样问题的其他人而没有发布答案).

事实证明,使用多态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
Run Code Online (Sandbox Code Playgroud)

这个关于多态has_many :through关联的另一个问题的答案是帮助我解决这个问题的.