Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 760
lyricat Avatar asked Jan 09 '11 20:01

lyricat


People also ask

What is a polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is Has_and_belongs_to_many?

Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use has_and_belongs_to_many, which allows you to make the association directly: The second way to declare a many-to-many relationship is to use has_many :through.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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

like image 79
Heikki Avatar answered Oct 06 '22 00:10

Heikki