Derptacos
Derptacos

Reputation: 177

Rails not recognizing relationships

Having issues trying to set up the relationship in my database.

I have a user and some comments (1:N)

Class User .. 
  ...
  has_many :comments
end

Class Comment .. 
 ..
 belongs_to :user
end

When attempting to assign comments to a user through the console and I enter the following : user.comments I receive the following error

 ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column:
 comments.user_id: SELECT "comments".* FROM "comments"  WHERE 
 "comments"."user_id" = 1

I have ran bundle exec db:test:prepare and my migrations as following

rails g migration CreateUsers ..... 

rails g migration CreateComments .....

I have tried db:schema:dump and migrating again but continuing to have the issues.

Upvotes: 0

Views: 74

Answers (2)

Ven
Ven

Reputation: 19040

If you added the belongs_to and has_many yourself, then you have to generate a migration for that to.

rails g migration add_user_id_to_comments user_id:int

Upvotes: 2

Sagar.Patil
Sagar.Patil

Reputation: 991

You need to add user_id in comment model

Upvotes: 0

Related Questions