如何仅选择具有关联标记记录的员工?换句话说,只选择具有一个或多个与其关联的标记记录的员工记录。
class Employee < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :employees
end
下面的查询(这是错误的)会让你们知道我要做什么
Employee.includes(:tags).where("tags.id != nil")
您可以使用.joins
Employee.joins(:tags)
此生成的SQL包含tags
表上的和INNER JOIN
,省略了没有关联tags
记录的employees
表记录。