ActiveRecord通过多个关系查询

时间:2016-09-21 05:29:18

标签: ruby-on-rails activerecord

我想查询哪里得到与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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用includes method

示例:

Article.includes(:category, :comments)