Decrypter
Decrypter

Reputation: 3000

Including multiple Associations in a query

I hope to explain my problem using the tables below:

university = University.where('class.name' => 'example', 'class.students.age' => '21').includes(:class, :student)

University
id
class.id
name

Class:
id
student.id
name
MaximumStudents

Student:
id
name
age

As you can see the University table references the Class table. The Class table references the Student table.

I want to get the universities that have a class called example and the students are aged 21. I know it weird but it shows my problem :D

I can't get my query to get hold of the Student. I always get the error "Association named 'students' was not found"

It works fine if I do the following without using the Student table

university = University.where('class.name' => 'example').includes(:class)

Upvotes: 0

Views: 31

Answers (1)

M. Cypher
M. Cypher

Reputation: 7066

First of all, be advised that it's not a good idea to name a model "Class" since that's a reserved word in Ruby (for classes), which may cause trouble.

Aside from that: In the University model, you need to specify a relation to the Student model like this:

has_many :students, :through => :class

Then you can get what you want with a relation like this:

university = University.where('class.name' => 'example', 'students.age' => 21).includes(:class, :students)

Upvotes: 2

Related Questions