Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find where associated records exist

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")
like image 944
primary0 Avatar asked Aug 22 '12 17:08

primary0


1 Answers

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.

like image 190
deefour Avatar answered Nov 16 '22 13:11

deefour