Rails的多态的has_many:通过 [英] Rails polymorphic has_many :through
问题描述
我是从一个外部API拉一些数据,并想在本地缓存的结果。我有一个类搜索关键词
,我想用几个不同的ActiveRecord类型,通过该表相关联 searchable_items
。我是pretty的肯定,我有表设置正确的事,但在我协会必须是错误的。
I'm pulling some data from an external API and would like to cache the results locally. I have a class SearchTerm
, which I would like to be associated with a few different ActiveRecord types through the table searchable_items
. I'm pretty sure I have the tables set up correctly, but something in my associations must be wrong.
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('搜索关键词')。可搜寻
(这将返回Foo和Bar对象的数组)然而, ,我得到的错误
找不到关联关系:在模型中搜索关键词searchable_items
I would expect to be able to do something like SearchTerm.find_by_term('SearchTerm').searchables
(and it would return an array of Foo and Bar objects) however, I get the error
Could not find the association :searchable_items in model SearchTerm
在此先感谢任何见解,你可以提供给我!
Thanks in advance for any insight you can provide to me!
推荐答案
您需要的has_many补充:searchable_items
协会富
,酒吧
和搜索关键词
模型,因为:通过=&GT; :searchable_items
选项是指联想
You need to add has_many :searchable_items
association to Foo
, Bar
and SearchTerm
models because :through => :searchable_items
option refers to that association.
<一个href="http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association">http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
这篇关于Rails的多态的has_many:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!