【问题标题】:Rails polymorphic has_many :throughRails 多态 has_many :through
【发布时间】:2011-06-06 04:54:18
【问题描述】:

我正在从外部 API 提取一些数据,并希望在本地缓存结果。我有一个class SearchTerm,我想通过表searchable_items 将它与几个不同的ActiveRecord 类型相关联。我很确定我的表格设置正确,但我的关联中一定有问题。

class Foo < ActiveRecord::Base
  has_many :search_terms, :as => :searchable, :through => :searchable_items
end

class Bar < ActiveRecord::Base
  has_many :search_terms, :as => :searchable, :through => :searchable_items
end

class SearchTerm < ActiveRecord::Base
  has_many :searchables, :through => :searchable_items
end

class SearchableItem < ActiveRecord::Base
  belongs_to :search_term
  belongs_to :searchable, :polymorphic => true
end

我希望能够执行 SearchTerm.find_by_term('SearchTerm').searchables 之类的操作(它会返回一个 Foo 和 Bar 对象数组)但是,我得到了错误 Could not find the association :searchable_items in model SearchTerm

提前感谢您提供给我的任何见解!

【问题讨论】:

    标签: ruby-on-rails activerecord polymorphic-associations


    【解决方案1】:

    您需要将has_many :searchable_items 关联添加到Foo、Bar 和SearchTerm 模型,因为:through =&gt; :searchable_items 选项指的是该关联。

    http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

    【讨论】:

    • 不幸的是,添加你的建议给Cannot have a has_many :through association 'SearchTerm#searchables' on the polymorphic object 'Searchable#searchable'.
    • 就像错误消息说的那样,你不能在多态对象上有很多通过关联。您可以对Foo 和Bar 进行单独的处理,就像上面的链接问题一样。
    • 链接的问题正是我想要的。谢谢海基。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多