Ruby on rails 如何在引用表没有id列的迁移中添加外键
我正在尝试向Rails项目添加一个新表,其中包含对其他表的多个引用。但是,外部表没有Ruby on rails 如何在引用表没有id列的迁移中添加外键,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我正在尝试向Rails项目添加一个新表,其中包含对其他表的多个引用。但是,外部表没有:id列;我将它们设置为每个都有一个字符串:code列作为主键 下面是我将要引用的一个表的示例: class-CreateReasons
:id
列;我将它们设置为每个都有一个字符串:code
列作为主键
下面是我将要引用的一个表的示例:
class-CreateReasons
由此产生的Postgres描述正是我想要的:
development-# \d reasons
Table "public.reasons"
Column | Type | Collation | Nullable | Default
-------------+-----------------------------+-----------+----------+---------
code | character varying | | not null |
description | character varying | | |
created_at | timestamp without time zone | | not null |
updated_at | timestamp without time zone | | not null |
Indexes:
"reasons_pkey" PRIMARY KEY, btree (code)
我想要的是我的新表,让我们称之为TestModel
,它有一个名为:reason\u code
的列,它是对reasons
表主键的外键引用
我尝试过的事情:
add_reference:test_models,:reasons,column::code,type::string,name::reasons_code,foreign_key:true
在表创建下面。错误为PG::UnfinedColumn:错误:外键约束中引用的列“id”不存在
add_foreign_key:test_models,:reasons,column::code,type::string,name::reasons_code
在表创建下面。错误为PG::UnfinedColumn:错误:外键约束中引用的列“code”不存在
t.references:reason\u code,外键:{to\u table::reasons}
和
t.references:reason\u code,foreign\u key:{to\u table::reasons,column::code}
两者都给出了错误PG::UndefinedColumn:error:外键约束中引用的列“id”不存在
class CreateReasons < ActiveRecord::Migration
def change
create_table :products, id: false do |t|
t.string :code, null: false
t.string :description
t.timestamps
end
add_index :products, :code, unique: true
end
end
class Reason < ApplicationRecord
self.primary_key = 'code'
end
class-CreateReasons
你的模型应该是这样的:
class CreateReasons < ActiveRecord::Migration
def change
create_table :products, id: false do |t|
t.string :code, null: false
t.string :description
t.timestamps
end
add_index :products, :code, unique: true
end
end
class Reason < ApplicationRecord
self.primary_key = 'code'
end
类原因
您应该能够在外键迁移中使用主键
选项,它默认为列id
,这就是出现错误的原因:
add_foreign_key :test_models, :reasons, column: :reason_code, primary_key: :code
请参阅
add_foreign_key
方法的文档,这里有关于它的更多信息出于好奇,为什么要省略id列?这看起来像是在自找麻烦(就像你现在正在经历的那样)。非常感谢你!对于其他试图做同样事情的人来说,完整的解决方案需要两个部分:1。在create\u table
命令中将列添加为字符串:t.string:reason\u code
2。将@edariedl中的行添加到表creation.best下面。我们仍然需要在这两个模型上指定has和belling_to属性,对吗?当然,如果您想访问这些模型中的相关记录。您只需在中正确设置外键
和主键
有许多
和属于
定义,即可使其正常工作。