Find where associated records exist

蹲街弑〆低调 提交于 2019-12-18 19:04:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!