Rails 多态 has_many :through
我正在从外部 API 提取一些数据,并希望在本地缓存结果。我有一个 类 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 对象的数组),但是,我收到错误 无法在模型 SearchTerm 中找到关联:searchable_items
预先感谢您向我提供的任何见解!
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
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 errorCould not find the association :searchable_items in model SearchTerm
Thanks in advance for any insight you can provide to me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
has_many :searchable_items
关联添加到Foo
、Bar
和SearchTerm
模型,因为:through = > :searchable_items
选项引用该关联。http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association< /a>
You need to add
has_many :searchable_items
association toFoo
,Bar
andSearchTerm
models because:through => :searchable_items
option refers to that association.http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association