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:
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:
add_foreign_key :detalleinveacs,
:invmtoproducto,
column: :codproducto,
primary_key: :some_column_other_than_id
Please see the documentation for further details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.