Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

activerecord - Rails polymorphic has_many :through

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...