使用 'id' 以外的其他字段添加自己的一对多关联

Add self one-to-many association using other fields except 'id'

我有一个模型Product,我想在这两个字段上实现自关联channel_advisor_product_idparent_product_id。但是当我调用 Product.last.child_products 时,它需要 id 而不是 parent_product_id

belongs_to :parent_product, class_name: 'Product', primary_key: "channel_advisor_product_id"

has_many :child_products, class_name: 'Product', foreign_key: "parent_product_id"

您正在使用 rails 控制台吗?

如果"yes"再次输入退出和"rails c",那么在控制台中:

Product.last.child_products

然后您会看到查询是否使用“id”或“parent_product_id”。

基本上问题是通过添加 primary_keyforeign_key 来解决的 在两个协会 parentchildren 上。现在 id 被排除在外,self association 对我提供的列工作正常。

belongs_to :parent, class_name: 'Product', primary_key: "channel_advisor_product_id", foreign_key: "parent_product_id"
has_many :children, class_name: 'Product', foreign_key: "parent_product_id", primary_key: "channel_advisor_product_id"