我试图在我的 Rails 4 项目中创建一个 Collaboration
表,但我遇到了一个问题。我希望它属于单个用户,即协作者。
我运行了以下命令来生成模型和迁移,我也在下面复制了这些命令。
rails generate model Collaboration project:references collaborator:references accepted:boolean
迁移:
class CreateCollaborations < ActiveRecord::Migration
def change
create_table :collaborations do |t|
t.references :project, index: true, foreign_key: true
t.references :collaborator, index: true, foreign_key: true
t.boolean :accepted
t.timestamps null: false
end
end
end
型号:
class Collaboration < ActiveRecord::Base
belongs_to :project
belongs_to :collaborator, class_name: 'User'
end
我更新了协作模型以包括 , class_name: 'User'
,如上所示。同样,我更新了现有的 Strategy
模型以包含 has_many :collaborations
class Project < ActiveRecord::Base
has_many :collaborations
end
当我运行 rake db:migrate
时,我收到以下错误报告。
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "collaborators" does not exist
我有点困惑为什么会这样。 如有任何帮助,我们将不胜感激!谢谢。 :)
编辑:
同时为我的 User
模型添加代码。
class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :projects
has_many :collaborations
end
我删除了密码、电子邮件等字段的验证以尝试消除困惑。
最佳答案
迁移的这一部分:
t.references :collaborator, index: true, foreign_key: true
将尝试创建一个 foreign key在数据库中,以便 collaborations
表的 collaborator_id
列将保证为 NULL
或包含 id
collaborators
表中的列。在 collaborators
表存在之前,您无法创建该 FK。
你得到的错误是:
relation "collaborators" does not exist
这只是告诉您您没有 collaborators
表,但您正在尝试引用它。
在创建 collaborations
表之前,您需要迁移以创建 collaborators
表。
关于ruby-on-rails - Rails 4 迁移 |添加引用表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32021638/