2

我有两个具有以下关联的模型:

  • 一个用户有很多项目。
  • 一个项目属于一个用户。

用户模型(user.rb):

 class User < ActiveRecord::Base
   has_many :projects
   attr_accessible :available, :department, :name, :skills, :title, :photo
 end

项目模型(project.rb):

class Project < ActiveRecord::Base
  belongs_to :user, :foreign_key => :user_id
  attr_accessible :project_name
end

外键迁移文件:

class AddForeignKeyToUsers < ActiveRecord::Migration
  def change
    add_column :users, :user_id, :integer
  end
end

当我打电话时,<%= @user.projects %>我收到此错误消息:

SQLite3::SQLException: no such column: projects.user_id: SELECT "projects".* FROM "projects"  WHERE "projects"."user_id" = 2
4

1 回答 1

2

您将外键添加到错误的表中。它应该在projects,而不是在users

class AddForeignKeyToProjects < ActiveRecord::Migration
  def change
    add_column :projects, :user_id, :integer
  end
end

由于您遵守约定,因此您不必在Project模型中指定外键。这应该足够了:

belongs_to :user
于 2012-11-12T07:02:19.220 回答