Rails多态has_many:通过

lyr*_*cat 15 activerecord ruby-on-rails polymorphic-associations

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

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
Run Code Online (Sandbox Code Playgroud)

我希望能够做类似的事情SearchTerm.find_by_term('SearchTerm').searchables(它会返回一个Foo和Bar对象的数组)然而,我得到了错误 Could not find the association :searchable_items in model SearchTerm

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

Hei*_*kki 11

您需要添加has_many :searchable_items关联Foo,Bar并且SearchTerm因为模型:through => :searchable_items的选择是指关联.

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

  • 类似的设置在这里:http://stackoverflow.com/questions/1683265/activerecord-has-many-through-and-polymorphic-associations (9认同)
  • 不幸的是,在多态对象'Searchable #searchable'中添加你建议的内容给出了"不能有一个has_many:通过关联'SearchTerm#searchables'. (7认同)
  • 就像错误消息所说的那样,你不可能在多态对象上有很多关联.在上面的链接问题中,您可以单独为"Foo"和"Bar"提供许多通道. (3认同)