2

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"?

1
  • As you can see in the reviews table there is no 'movie_id' column but instead there is a "movies_id". Commented Feb 22, 2013 at 23:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.