Rails 多态 has_many :through

发布于 2024-10-11 00:32:45 字数 850 浏览 7 评论 0原文

我正在从外部 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 error
Could not find the association :searchable_items in model SearchTerm

Thanks in advance for any insight you can provide to me!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久光 2024-10-18 00:32:45

您需要将 has_many :searchable_items 关联添加到 FooBarSearchTerm 模型,因为 :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 to Foo, Bar and SearchTerm models because :through => :searchable_items option refers to that association.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文