在Rails迁移中指定自定义引用键名称

时间:2016-12-24 23:10:57

标签: ruby-on-rails-4 activerecord

我尝试为product_code表创建自定义主键products,而不是允许Rails将表默认为使用idproducts表与has_one表具有metrics关系,但是当我使用belongs_to指定:product生成迁移时 - 我的数据库中的外键是product_id而不是product_code。如何生成迁移并强制foreign_key表中的metricsproduct_code而不是product_id

我有以下迁移和模型关系。

# 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

1 个答案:

答案 0 :(得分: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