ruby-on-rails - has_many :through 的源反射错误

标签 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,在三个地方出现错误:
  • 第一次加载仪表板 (/admin) 时。如果我刷新页面,它工作正常。
  • 在 Rails_Admin 中加载 User 模型时
  • 在 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/

    相关文章:

    javascript - 在我的 Handlebars 模板加载完成之前,如何才能完成 AJAX 调用?

    ruby-on-rails - 重命名 Ruby on Rails 应用程序

    ruby-on-rails - Rails 和电子表格导入/导出

    node.js - 如何使用sails.js 为模型定义实例方法

    ruby-on-rails - Rails 5 获取关联的关联

    ruby-on-rails - Ruby on Rails : What is the opposite of the build method? 或者,我可以在保存对象之前从内存中销毁它吗?

    mysql - 使用 __construct 更新模型以限制返回结果

    python - 如何使用多个分类变量以 Python R 风格创建预测模型

    ruby-on-rails - 潜在无限类型的多态关联

    ruby-on-rails - 销毁 Active Record 中的孤立多态关联