Rails foreign_key不是id

时间:2018-08-28 11:08:28

标签: ruby-on-rails ruby associations

我有两个桌子

class Sku < ApplicationRecord
  validates :sku, :supplier_code, :name, :price, presence: true
  belongs_to :supplier, class_name: 'Supplier', foreign_key: 'code'
end

 class Supplier < ApplicationRecord
  validates :code, :name, presence: true
  has_many :skies, class_name: 'Sku'
end

我将foreign_key设置为code字段

但是当我尝试使用我设置为供应商的sku创建supplier_code

Supplier.create(code:4,name:2) => OK

我遇到错误{:supplier=>[{:error=>:blank}]},

Sku.create(name:2,price:2,sku:3,supplier_code:4).errors

1 个答案:

答案 0 :(得分:0)

您必须在另一个模型上进行定义

class Sku < ApplicationRecord
  validates :sku, :supplier_code, :name, :price, presence: true
  belongs_to :supplier, class_name: 'Supplier', foreign_key: 'code'
end

class Supplier < ApplicationRecord
  validates :code, :name, presence: true
  has_many :skies, class_name: 'Sku', primary_key: 'id', foreign_key: 'code'
end