簡體   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