繁体   English   中英

如何使用现有的柱形导轨定义迁移参考?

[英]how to define reference on migration with an existing column rails?

我想使用现有列定义模型迁移的外键,我想将 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

如果外键引用的列与invmtoproducto表上的id不同,则可以覆盖该默认值:

add_foreign_key :detalleinveacs, 
                :invmtoproducto, 
                column: :codproducto,
                primary_key: :some_column_other_than_id

请参阅文档以获取更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM