Gilad Naaman
Gilad Naaman

Reputation: 6550

Rails - Model association generates an invalid SQL query

I have a rails app in which one model was built like this

class Forum::Thread < ActiveRecord::Base
  belongs_to :forum
  belongs_to :user
  attr_accessible :body, :title

  has_many :comments, dependent: :destroy
end

In some point I've realized that user is not a good name, so I've changed it to author.

class Forum::Thread < ActiveRecord::Base
  belongs_to :forum
  belongs_to :author, class_name: 'User'
  attr_accessible :body, :title

  has_many :comments, dependent: :destroy
end

Also, in user I have the following:

has_many :forum_threads, class_name: 'Forum::Thread', inverse_of: :author

But when I try to fetch the list of threads (@user.forum_threads, for example), it seems like rails still builds a query that refers to the old user_id instead for the new author_id.

 Showing /home/giladnaaman/Programming/Eclipse/Hephaestus/app/views/users/show.html.erb where line #40 raised:

SQLite3::SQLException: no such column: forum_threads.user_id: SELECT COUNT(*) FROM "forum_threads"  WHERE "forum_threads"."user_id" = 1

Extracted source (around line #40):

37:                         # of Threads
38:                     </dt>
39:                     <dd>
40:                         <%= @user.forum_threads.count%> <%= link_to 'watch', '#', class: 'btn btn-mini pull-right'%>
41:                     </dd>
42:                     <br />
43:                     <dt>

What can I do to fix this?

Upvotes: 0

Views: 94

Answers (2)

Przemek Mroczek
Przemek Mroczek

Reputation: 357

Maybe you should use the foreign key and by foreign key I mean the "user_id"

Upvotes: 1

FluffyJack
FluffyJack

Reputation: 1732

Maybe try setting the foreign_key? http://guides.rubyonrails.org/association_basics.html#options-for-belongs_to

Upvotes: 0

Related Questions