[英]Rails polymorphic has_many :through
我從外部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
提前感謝您提供給我的任何見解!
您需要將has_many :searchable_items
關聯添加到Foo
, Bar
和SearchTerm
模型,因為:through => :searchable_items
選項指的是該關聯。
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.