我试图在Rails 4项目中创建一个Collaboration表,但遇到了一个问题。我希望它能belong_to一个用户,即协作者。
我运行了下面的命令来生成模型和迁移,下面我也复制了这个命令。
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我编辑了诸如密码、电子邮件等字段的验证,以试图消除混乱。
发布于 2015-08-15 05:26:46
迁移的这一部分:
t.references :collaborator, index: true, foreign_key: true将尝试在数据库中创建外键,以便保证collaborations表的collaborator_id列为NULL或在collaborators表中包含列的id。在collaborators表存在之前,不能创建FK。
您所遇到的错误是:
relation "collaborators" does not exist这只是告诉您,您没有collaborators表,但您正在尝试引用它。
在创建collaborators表之前,需要进行迁移才能创建collaborations表。
发布于 2018-03-14 19:31:20
至少在Rails 5中,您可以使用foreign_key:{to_table:.}如下所示。
create_table :messages, id: :uuid do |t|
t.references :from_user, type: :uuid, index: true, null: false, foreign_key: {to_table: :users, on_delete: :cascade}
t.references :to_user, type: :uuid, references: :user, index: true, null: false, foreign_key: {to_table: :users, on_delete: :cascade}
t.text :body, null: false
t.timestamps
end发布于 2020-12-24 19:47:14
抱歉迟到了,但本质上是为了方便,记住这是rails的本质。因此,每个引用都应该针对应该是复数的表(因为一个表包含许多“对象”),因此必须对复数进行引用,这样rails将生成对单个对象的引用。按钮行,你的迁移应该更像;
class CreateCollaborations < ActiveRecord::Migration
def change
create_table :collaborations do |t|
t.references :projects, index: true, foreign_key: true
t.references :collaborators, index: true, foreign_key: true
t.boolean :accepted
t.timestamps null: false
end
end
end现在,如果您遵循这些约定,那么您应该不会有其他的问题,只需记住,belong_to对于一个单数对象来说,has_many是一个复数对象。
PS:我不会用过去的引用作为专栏的参考,比如accepted
快乐编码
https://stackoverflow.com/questions/32021638
复制相似问题