1
votes

Given the following code from the book ruby on rails tutorial (rails 5)

class User < ApplicationRecord
  has_many :microposts
end

class Micropost < ApplicationRecord
  belongs_to :user 
  validates :content, length: { maximum: 140 }
end

After executing actions in the console, I have such an error.

Traceback (most recent call last): ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: microposts.user_id: SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? LIMIT ?)

Can someone please help me clarify what the problem is?

1
Can you include your migrations, as well as whether the migrations have been run?Chris J
check whether you missed to add user_id or association to user inside your microposts migration and also update code from has_many :micropost to has_many :microposts inside your User modelVishal Taj PM

1 Answers

0
votes

For belongs_to association, you need a foreign_key in your table.

It seems that you have not added user_id column in a microposts table or if added then check whether migration is executed or not.

Also check the foreign key name is specified correctly