我有两个桌子
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
答案 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