LewlSauce
LewlSauce

Reputation: 5872

How to use "where" to get parent of parent that has attribute of XYZ

Using ajax-datatables-rails, I am trying to get records that are children of a parent model.

For example, I have a parent model named School, which has many teachers, each of which has many students.

If I am using Student.joins(:teacher), but teacher belongs to school, how can I write this so that it only pulls back the students that belong to teachers which belong to a certain school.

I am trying to find a way to do something like: Student.joins(:teacher => [:school where school_name == "hello world"]) although I know this isn't the right syntax.

Here's the model structure:

# app/models/school.rb
class School < ApplicationRecord
    has_many :teachers
end

.

# app/models/teacher.rb
class Teacher < ApplicationRecord
    belongs_to :school
    has_many :students
end

.

# app/models/student.rb
class Student < ApplicationRecord
    belongs_to :teacher
end

Upvotes: 0

Views: 32

Answers (2)

Vishal Taj PM
Vishal Taj PM

Reputation: 1359

You can also use has_many through association to achieve this. Reference

app/models/school.rb

class School < ApplicationRecord
  has_many :teachers
  has_many :students, through: :teachers
end

app/models/teacher.rb

class Teacher < ApplicationRecord
    belongs_to :school
    has_many :students
end

app/models/student.rb

class Student < ApplicationRecord
  belongs_to :teacher
end

So let's say you want to get students list of a particular school can query like.

School.find_by_name('ABC School').students

Upvotes: 0

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

Do the joins first and then filter on the table you're interested in:

Student.joins(teacher: :school).where(schools: { name: "hello world" })

Upvotes: 1

Related Questions