15

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!

Ryan Ahearn
  • 7,886
  • 7
  • 51
  • 56
lyricat
  • 1,988
  • 2
  • 12
  • 20

1 Answers1

11

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

Heikki
  • 15,329
  • 2
  • 54
  • 49
  • 7
    Unfortunately, adding what you suggested gives `Cannot have a has_many :through association 'SearchTerm#searchables' on the polymorphic object 'Searchable#searchable'.` – lyricat Jan 09 '11 at 21:03
  • 9
    Similar setup here: http://stackoverflow.com/questions/1683265/activerecord-has-many-through-and-polymorphic-associations – Heikki Jan 09 '11 at 21:08
  • 3
    Like the error message says, you cannot have has many through association on polymorpic object. You could have separate has many throughs for `Foo` and `Bar` like in the linked question above. – Heikki Jan 09 '11 at 21:27
  • The linked question is exactly what I was looking for. Thanks Heikki. – lyricat Jan 10 '11 at 00:06