寻找到相关记录存在 [英] Find where associated records exist

查看:98
本文介绍了寻找到相关记录存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以只选择那些谁相关标签记录的员工呢?换句话说,只有选择那些与它们相关联的一个或多个标签记录员工的记录。

 类Employee<的ActiveRecord :: Base的
  has_and_belongs_to_many:标签
结束

类标签<的ActiveRecord :: Base的
  has_and_belongs_to_many:雇员
结束
 

下面的查询(这是错误的)会给你们的什么,我试图做一个想法。

  Employee.includes(:标签)。凡(!tags.id =无)
 

解决方案

您可以使用<一个href="http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-joins"><$c$c>.joins

  Employee.joins(:标签)
 

在SQL中,生成包含与 INNER JOIN 标签表,省略员工谁没有相关的标签表中的记录的记录。

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.

这篇关于寻找到相关记录存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆