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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With