bull
bull

Reputation: 23

Rails foreign_key not id

I have two tables

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

and

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

i set foreign_key as a code field

but when i tried to create sku with supplier_code which i set to supplier

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

i have got an error {:supplier=>[{:error=>:blank}]},

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

Upvotes: 0

Views: 46

Answers (1)

Vishal
Vishal

Reputation: 7361

You must need to define on another model

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

and

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

Upvotes: 1

Related Questions