J. Doe
J. Doe

Reputation: 563

Strange issue with setting custom foreign_key

From the documentation I read that:

class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron", foreign_key: "patron_id"
end

so according to that I'm trying the next:

class Choco < ActiveRecord::Base
  has_many :kinds, inverse_of: :choco, foreign_key: :myhash

and

class Kind < ActiveRecord::Base
  belongs_to :choco, foreign_key: :myhash

But instead it pastes in that column NULL and I cannot understand why.

Schema

For Choco:

— (id, title, myhash)

For Kind:

— (id, choco_id, title)

I want to paste myhash on choco_id field on creating a new kind.

What is the problem?

Upvotes: 1

Views: 39

Answers (1)

Thanh
Thanh

Reputation: 8624

You can specify primary key to store on Kind model:

class Choco < ActiveRecord::Base
  self.primary_key = 'myhash'
  has_many :kinds, inverse_of: :choco, primary_key: :myhash


class Kind < ActiveRecord::Base
  belongs_to :choco, primary_key: :myhash

So choco_id column in Kind model will store myhash value of choco.

Upvotes: 1

Related Questions