Rails 多态 has_many :through [英] Rails polymorphic has_many :through

查看:21
本文介绍了Rails 多态 has_many :through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从外部 API 中提取一些数据,并希望在本地缓存结果.我有一个 class SearchTerm,我想通过表 searchable_items 将它与几个不同的 ActiveRecord 类型相关联.我很确定我的表格设置正确,但我的关联中一定有问题.

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('SearchTerm').searchables 的操作(并且它会返回一个 Foo 和 Bar 对象数组)但是,我收到了错误在模型 SearchTerm 中找不到关联: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 关联添加到 Foo, BarSearchTerm 模型,因为 :through =>: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.

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

这篇关于Rails 多态 has_many :through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆