has_many的源反射错误:通过

时间:2013-05-21 19:11:59

标签: ruby-on-rails model polymorphic-associations model-associations rails-admin

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

用户模型:

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,我在三个地方收到错误:

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

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

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

2 个答案:

答案 0 :(得分:11)

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

事实证明,使用多态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关联的另一个问题是帮助我解决这个问题的原因。

答案 1 :(得分:4)

当代码包含一个不存在的关联的has_many时(中间重构),我遇到了这个错误。所以它也可能是由于一些常见的has_many错误配置造成的。 Ruby / Rails代码从不关心,因为Ruby的动态样式意味着只能按需调用关联。但是Rails-Admin会彻底检查属性,从而导致反射问题。