如何使用现有的列栏定义有关移植的参考?
问题描述:
我想用现有的列来定义模型迁移外键,我想设置codproducto作为表称为invmtoproducto的外键,这是我的新模式迁移:如何使用现有的列栏定义有关移植的参考?
class CreateDetalleinveacs < ActiveRecord::Migration[5.1]
def change
create_table :detalleinveacs do |t|
t.integer :correlativo
t.integer :cantidad
t.decimal :valor, precision: 20, scale: 10
t.decimal :costo, precision: 30, scale: 20
t.string :nis
t.datetime :feacceso
t.integer :codproducto
t.integer :idinveac
end
end
end
答
您可以使用
add_foreign_key :detalleinveacs, :invmtoproducto, column: :codproducto
你的迁移则是这样的:
class CreateDetalleinveacs < ActiveRecord::Migration[5.1]
def change
create_table :detalleinveacs do |t|
t.integer :correlativo
t.integer :cantidad
t.decimal :valor, precision: 20, scale: 10
t.decimal :costo, precision: 30, scale: 20
t.string :nis
t.datetime :feacceso
t.integer :codproducto
t.integer :idinveac
end
# Add a foreign key constraint
# from the 'detalleinveacs' table
# to the 'invmtoproducto' table
# where the foreign key column 'codproducto' of the 'detalleinveacs' table
# references the 'id' column of the 'invmtoproducto' table.
add_foreign_key :detalleinveacs, :invmtoproducto, column: :codproducto
end
end
万一外键引用超过01不同的列上invmtoproducto
表,它可以覆盖该默认:
add_foreign_key :detalleinveacs,
:invmtoproducto,
column: :codproducto,
primary_key: :some_column_other_than_id
请参阅documentation进一步的细节
林不知道我应该在哪里添加此,我尝试创建表的外块,但它不工作,这是一个特定的命令还是应该在迁移中? – AlexQuezada
@AlexQuezada我详细阐述了可能性。特别是,我添加了选项来指定除'id'之外的primary_key,因为您的表可能不遵循默认的命名约定。如果这还不够,请说明错误,以便我可以提供一些具体的建议。 – ulferts
谢谢,它的工作!我有一个错误,因为在invmtoproducto表的约束没有定义,但一旦我修复它的工作就像一个魅力! – AlexQuezada