ruby-on-rails – 使用add_foreign_key进行Rails迁移:外键约束
发布时间:2020-12-16 21:06:31 所属栏目:百科 来源:网络整理
导读:(Rails是5.0.0版,Ruby 2.3.0p0) 我想在Users表和Cards表之间创建一个关联.我已将belongs_to:user添加到Cards模型,并将has_many:cards添加到Users模型,并创建了一个迁移: class AddUserIdToCard ActiveRecord::Migration[5.0] def change add_foreign_key
(Rails是5.0.0版,Ruby 2.3.0p0)
我想在Users表和Cards表之间创建一个关联.我已将belongs_to:user添加到Cards模型,并将has_many:cards添加到Users模型,并创建了一个迁移: class AddUserIdToCard < ActiveRecord::Migration[5.0] def change add_foreign_key :cards,:users,column: :user_id end end 当我运行rake db:migrate时,我收到错误: ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "user_id" referenced in foreign key constraint does not exist : ALTER TABLE "cards" ADD CONSTRAINT "fk_rails_8ef7749967" FOREIGN KEY ("user_id") REFERENCES "users" ("id") 现在我最初只是通过在迁移中添加add_column:cards,:user_id,:integer来解决这个问题,但这看起来并不是很整洁,而且我担心以后会出现问题.有没有更好的方法来实现这一目标? 解决方法
您正在使用列user_id为cards表设置外键.但是你还没有创建引用.创建引用,然后添加外键以维护引用完整性.使用回滚并修改您的迁移
1 class AddUserIdToCard < ActiveRecord::Migration[5.0] 2 def change 3 add_reference :cards,index:true 4 add_foreign_key :cards,:users 5 end 6 end 第3行将在cards表中创建对users表中id的引用(通过在cards中创建user_id列). 第4行将在数据库级别向user_id添加外键约束. 有关更多信息,请阅读Add a reference column migration in Rails 4 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |