ConorB ConorB - 1 year ago 112
Ruby Question

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 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!

Answer Source

Yep, that's absolutely possible:

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

See the docs for more info on the topic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download