Conor
Conor

Reputation: 3579

ActiveRecord: Filter record by nested record attribute

In my Rails application I have 2 models: Students and Courses.

Students have many courses.

Running the command Student.first.courses into the rails console would result in a collection of the courses belonging to the first student being returned.

What I'm wondering is if it's possible to write a command that would check if there were any students with a particular course.

For example if I wanted to see if there were any students with 'English' as one of their courses, how would I write this?

Any help would be much appreciated - thanks!

Upvotes: 0

Views: 161

Answers (2)

John W
John W

Reputation: 21

Following on from Andrey's answer, you can wrap that up in a scope within your Student model, like this:

scope :taking, ->(subject_name) { joins(:courses).where(courses: {name: subject_name})}

and then use it with:

Student.taking("English")

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52357

Yep, that's absolutely possible:

Student.joins(:courses).where(courses: { name: 'English' })

See the docs for more info on the topic.

Upvotes: 4

Related Questions