查找存在关联记录的位置
如何仅选择那些具有关联标记记录的员工? 换句话说,仅选择具有与之关联的一个或多个标记记录的员工记录。
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)
这会在tags
表上生成包含和INNER JOIN
的SQL,省略没有关联tags
记录的employees
表记录。