[英]how to define reference on migration with an existing column rails?
I want to define the foreign key for a model migration using an existing column,I want to set codproducto as foreign key of a table called invmtoproducto, here is my new model migration:我想使用现有列定义模型迁移的外键,我想将 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
You can use您可以使用
add_foreign_key :detalleinveacs, :invmtoproducto, column: :codproducto
Your migration would then look like this:您的迁移将如下所示:
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
In case the foreign key references a column different than id
on the invmtoproducto
table, it is possible to override that default:如果外键引用的列与invmtoproducto
表上的id
不同,则可以覆盖该默认值:
add_foreign_key :detalleinveacs,
:invmtoproducto,
column: :codproducto,
primary_key: :some_column_other_than_id
Please see the documentation for further details请参阅文档以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.