2017-09-26 31 views
0

我想用現有的列來定義模型遷移外鍵,我想設置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 

回答

0

您可以使用

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進一步的細節

+0

林不知道我應該在哪裏添加此,我嘗試創建表的外塊,但它不工作,這是一個特定的命令還是應該在遷移中? – AlexQuezada

+0

@AlexQuezada我詳細闡述了可能性。特別是,我添加了選項來指定除'id'之外的primary_key,因爲您的表可能不遵循默認的命名約定。如果這還不夠,請說明錯誤,以便我可以提供一些具體的建議。 – ulferts

+0

謝謝,它的工作!我有一個錯誤,因爲在invmtoproducto表的約束沒有定義,但一旦我修復它的工作就像一個魅力! – AlexQuezada