通过多个关系进行ActiveRecord查询

问题描述 投票:0回答:2

我想查询所有与 D 类相关的 A 类,并具有特定的名称(D 类有名称列)。但之间也有 B 类和 C 类,实际上我不知道如何通过连接和合并来处理这个问题。

关系如下:

class Appointment
 has_many :booked_classes
 has_many :classes, through: :booked_classes
end

class BookedClass
 belongs_to :Appointment
 belongs_to :Class
end

class Class
 belongs_to :Teacher
 has_many: BookedClasses
end

class Teacher
 has_many :Appointmentss, through :Clasesses
 has_many :Classes
end
ruby-on-rails activerecord
2个回答
0
投票

你可以试试这个:

Appointment.joins(classes: [:teacher]).where(teachers: { name: "your_name" }) #"your_name" is the name to be matched with the value in name column of Ds table

0
投票

使用包含方法

示例:

Article.includes(:category, :comments)
© www.soinside.com 2019 - 2024. All rights reserved.