Harry Moreno
Harry Moreno

Reputation: 11603

rails no such column error

I have the following app. A Movie has many reviews, a moviegoer has many reviews. When I try to associate a review with a movie I get the following error

Review Load (0.1ms)  SELECT "reviews".* FROM "reviews" WHERE "reviews"."movie_id" = 5
SQLite3::SQLException: no such column: reviews.movie_id: SELECT "reviews".* FROM     "reviews"  WHERE "reviews"."movie_id" = 5
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: reviews.movie_id:     SELECT "reviews".* FROM "reviews"  WHERE "reviews"."movie_id" = 5

after using a sql gui editor I found that the correct query should be

SELECT "reviews".* FROM "reviews" WHERE "movie_id" = 5

review.rb

class Review < ActiveRecord::Base
  belongs_to :movie
  belongs_to :moviegoer
  attr_protected :moviegoer_id
end

movie.rb and moviegoer.rb have

has_many :reviews

in them. schema.rb

ActiveRecord::Schema.define(:version => 20130222225620) do

create_table "moviegoers", :force => true do |t|
t.string   "name"
t.string   "provider"
t.string   "uid"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

create_table "movies", :force => true do |t|
t.string   "title"
t.string   "rating"
t.text     "description"
t.datetime "release_date"
t.datetime "created_at",   :null => false
t.datetime "updated_at",   :null => false
end

create_table "reviews", :force => true do |t|
t.integer "potatoes"
t.text    "comments"
t.integer "moviegoers_id"
t.integer "movies_id"
end

end

What am I doing wrong? why is rails querying "reviews"."movie_id" instead of just "movie_id"?

Upvotes: 2

Views: 2896

Answers (1)

Cluster
Cluster

Reputation: 5616

You have the wrong column name in your migration. The rails convention is that foreign keys are to be singular. If they are not then you need to tell rails what the foreign key is with an options hash on the association.

Either rollback your migration, fix the column name (moviegoers_id is wrong as well) then migrate again, or tell rails the foreign key.

Class Review < ActiveRecord::Base
  belongs_to :movie, :foreign_key => 'movies_id'
  belongs_to :moviegoer, :foreign_key => 'moviegoers_id'
end

And the same has to happen on the has many side of both models.

Upvotes: 3

Related Questions