问题
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")
回答1:
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.
来源:https://stackoverflow.com/questions/12078819/find-where-associated-records-exist