2016-12-24 37 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 
相关问题