Ruby-on-rails Rails 多态 has_many :through

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4641500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:03:02  来源:igfitidea点击:

Rails polymorphic has_many :through

ruby-on-railsactiverecordpolymorphic-associations

提问by lyricat

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.

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

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

我希望能够做类似的事情SearchTerm.find_by_term('SearchTerm').searchables(它会返回一个 Foo 和 Bar 对象的数组)但是,我得到了错误 Could not find the association :searchable_items in model SearchTerm

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

在此先感谢您提供给我的任何见解!

采纳答案by Heikki

You need to add has_many :searchable_itemsassociation to Foo, Barand SearchTermmodels because :through => :searchable_itemsoption refers to that association.

您需要将has_many :searchable_items关联添加到Foo,BarSearchTerm模型,因为:through => :searchable_itemsoption 指的是该关联。

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

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