Find where associated records exist

activerecord, ruby, ruby-on-rails

Solution

You can use `.joins`

Employee.joins(:tags)

The SQL this generates contains and `INNER JOIN` on the `tags` table, omitting `employees` table records who have no associated `tags` record.

Problem

How can I select only those Employees who have associated Tag records? In other words, only select employee records that have one or more tag records associated with them. ``` class Employee < ActiveRecord::Base has_and_belongs_to_many :tags end class Tag < ActiveRecord::Base has_and_belongs_to_many :employees end ``` The query below (which is wrong) will give you guys an idea of what I'm trying to do. ``` Employee.includes(:tags).where("tags.id != nil") ```

Original source