设置自定义的奇怪问题 foreign_key

Strange issue with setting custom foreign_key

从文档中我读到:

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

所以我正在尝试下一个:

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

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

但是它在该列中粘贴了 NULL,我不明白为什么。

架构

对于乔科:

— (id, title, myhash)

种类:

— (id, choco_id, title)

我想将 myhash 粘贴到创建新种类的 choco_id 字段中。

有什么问题?

您可以指定要存储在 Kind 模型上的主键:

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

因此 Kind 模型中的 choco_id 列将存储 choco 的 myhash 值。