Rails多态has_many:通过

时间:2011-01-09 20:13:32

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

我从外部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

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

1 个答案:

答案 0 :(得分:11)

您需要将has_many :searchable_items关联添加到FooBarSearchTerm模型,因为:through => :searchable_items选项指的是该关联。

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

相关问题