2016-12-24 4 views
1

を使用するようにRailsでデフォルト設定するのではなく、テーブルのカスタムプライマリキーproduct_codeを作成しようとしました。 productsテーブルはmetricsテーブルとの間にhas_oneの関係がありますが、belongs_toを指定して:productを指定してマイグレーションを生成すると、データベースの外部キーはproduct_codeではなくproduct_idになります。移行を生成してmetricsテーブルのforeign_keyproduct_idではなくproduct_codeにするにはどうすればよいですか?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

:あなたのProductMetricモデルで

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 

を、あなたも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 
関連する問題