has_many:通过class_name和foreign_key无效

问题描述

我需要创建父母关系,即客户模型中的孩子和父母关系。为了存储有关父母和孩子的信息,我创建了一个联接表,即ParentalRelation。 我的客户模型是:

class Customer < ApplicationRecord
  has_many :parental_relations
  has_many :children,class_name: 'Customer',foreign_key: 'child_id',through: :parental_relations
  has_one :parent,foreign_key: 'parent_id',through: :parental_relations,source: :parent
end

我的parental_relation模型是:

class ParentalRelation < ApplicationRecord
  belongs_to :parent,class_name: 'Customer'
  belongs_to :child,class_name: 'Customer'
end

我正在尝试通过以下方式获取数据:

Customer.first.children

但是我没有得到数据。即使有数据也会变得像这样:

Customer :: ActiveRecord_Associations_CollectionProxy:0x3fe49a819750

如果有人可以帮助我,那将是非常有用的帮助。预先谢谢你

解决方法

如果parent_relation具有列parent_idchild_id 我相信应该是

class Customer < ApplicationRecord
  has_many :children_relations,class_name: 'ParentalRelation',foreign_key: 'parent_id'
  has_many :children,class_name: 'Customer',foreign_key: 'parent_id',through: :children_relations,source: :child
  
  has_one :parent_relation,foreign_key: 'child_id'
  has_one :parent,through: :parent_relation,source: :parent
end

根据您的关系,Rails将执行SQL SELECT "customers".* FROM "customers" INNER JOIN "parental_relations" ON "customers"."id" = "parental_relations"."child_id" WHERE "parental_relations"."customer_id" = $1 LIMIT $2

但是我不知道您的表结构。因此,您可以在Rails控制台中阅读sql并了解Rails如何查找记录。它应该可以帮助您解决此问题。

,

鉴于您的模型中有customer has_one :parent,看来您正在尝试建立一对多关系。如果正确,则不需要联接表。如果要创建多对多关系,则仅需要一个联接表。

要以一对多的方式执行此操作,请删除ParentalRelation模型和表,然后将您的客户类别更新为以下形式:

class Customer < ApplicationRecord
  belongs_to parent,class_name: "Customer"
  has_many children,class_name: "Customer",foreign_key: :parent_id
end

在此处查看有关创建自联接表的指南: https://guides.rubyonrails.org/association_basics.html#self-joins

一旦有了,就应该能够做到:

Customer.first.children

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...