cognalog
cognalog

Reputation: 440

has_many...:through association not working despite proper modelling

I am writing a keyword search algorithm. The keywords are stored in the keywords table/model, and submissions (in which the searching takes place) are stored in the submissions table/model. There is also a submission_keywords table that links submissions to keywords via their unique ids in accordance with (what I'm pretty sure is) the has_many :through setup. However, when I try to display the keywords for a submission in my Show view:

<p>
  <b>Keywords:</b>
  <% @submission.keywords.each do |kw| %>
  <%= kw.name %>
  <% end %>
</p>

I get an error:

ActiveRecord::HasManyThroughAssociationNotFoundError
Could not find the association :submission_keyword in model Submission

Here is my code for these 3 models:

Submission.rb:

class Submission < ActiveRecord::Base
  attr_accessible :count, :is_sent, :is_success, :stamp, :url
  has_many :submission_keywords, :dependent => :destroy
  has_many :keywords, :through => :submission_keyword
end

Keyword.rb:

class Keyword < ActiveRecord::Base
  attr_accessible :name, :priority, :type
  has_many :submission_keywords, :dependent => :destroy
  has_many :submissions, :through => :submission_keyword
end

Submission_Keyword.rb

class SubmissionKeyword < ActiveRecord::Base
  attr_accessible :freq, :keyword_id, :submission_id, :weight
  belongs_to :submission
  belongs_to :keyword
end

and here is the code that requests the keywords for a submission in the view:

I've seen a lot of posts where people forgot to include a has_many association with the :through model, but as you can see I covered that. Any idea what could be going wrong?

Upvotes: 0

Views: 204

Answers (1)

kiddorails
kiddorails

Reputation: 13014

Just a little mistake. It should have been:

has_many :keywords, :through => :submission_keywords

and

has_many :submissions, :through => :submission_keywords

Notice submission_keyword*s*

Upvotes: 2

Related Questions