I have two models with the following associations:
- A user has many projects.
- A project belongs to a user.
User model (user.rb):
class User < ActiveRecord::Base
has_many :projects
attr_accessible :available, :department, :name, :skills, :title, :photo
end
Project model (project.rb):
class Project < ActiveRecord::Base
belongs_to :user, :foreign_key => :user_id
attr_accessible :project_name
end
Foreign key migration file:
class AddForeignKeyToUsers < ActiveRecord::Migration
def change
add_column :users, :user_id, :integer
end
end
When I call <%= @user.projects %> I get this error message:
SQLite3::SQLException: no such column: projects.user_id: SELECT "projects".* FROM "projects" WHERE "projects"."user_id" = 2
You added the foreign key to the wrong table. It should be in
projects, not inusers:Since you are sticking to the convention, you don’t have to specify the foreign key in your
Projectmodel. This should be enough: