2016-12-24 35 views
1

我試圖爲我的products表創建自定義主鍵product_code,而不是允許Rails將表默認爲使用idproducts表與metrics表的關係爲has_one,但是當我使用belongs_to指定:product生成遷移時 - 我的數據庫中的外鍵是product_id而不是product_code。如何生成遷移並強制metrics表中的foreign_keyproduct_code而不是product_id在Rails遷移中指定自定義引用密鑰名稱

我有以下遷移和模型關係。

# Product migration 
class CreateProducts < ActiveRecord::Migration 
    def change 
    create_table :products, id: false do |t| 
     t.string :product_code, null: false 
     t.timestamps null: false 
    end 
    add_index :products, :product_code, unique: true 
    end 
end 

# models/product.rb 
class Product < ActiveRecord::Base 
    self.primary_key :product_code 
    has_one :metric 
end 

# Metric migration 
class CreateMetrics < ActiveRecord::Migration 
    def change 
    create_table :metrics do |t| 
     t.belongs_to :product 
     t.string :department 
     t.timestamps null: false 
    end 
    end 
end 

# models/metric.rb 
class Metric < ActiveRecord::Base 
    belongs_to :product 
end 

回答

0

你可以試試:

class CreateMetrics < ActiveRecord::Migration 
    def change 
    create_table :metrics do |t| 
     t.string :department 
     t.timestamps null: false 
    end 
    add_foreign_key :metrics, : products, column: : product_code, primary_key: "product_code" 
    end 
end 

在你ProductMetric車型,你還應該指定foreign_key

class Product < ActiveRecord::Base 
    self.primary_key :product_code 
    has_one :metric, foreign_key: 'product_code' 
end 

class Metric < ActiveRecord::Base 
    belongs_to :product, foreign_key: 'product_code' 
end 
相關問題