ActiveRecord 查找所有关联孩子的父母 [英] ActiveRecord find all parents that have associated children

查看:35
本文介绍了ActiveRecord 查找所有关联孩子的父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么我无法弄清楚这一点,我认为应该相当简单.我有两个模型(见下文).我正在尝试为 SupplierCategory 提出一个命名范围,它可以找到所有与供应商关联的供应商类别(包括:供应商)不为空.

I don't know why I can't figure this out, I think it should be fairly simple. I have two models (see below). I'm trying to come up with a named scope for SupplierCategory that would find all SupplierCategory(s) (including :suppliers) who's associated Supplier(s) are not empty.

我尝试了直接连接,named_scope :with_suppliers, :joins =>:suppliers 它只给我提供带有供应商的类别,但它给了我单独列出的每个类别,所以如果一个类别有 2 个供应商,我会在返回的数组中获得该类别两次:

I tried a straight up join, named_scope :with_suppliers, :joins => :suppliers which gives me only categories with suppliers, but it gives me each category listed separately, so if a category has 2 suppliers, i get the category twice in the returned array:

目前我正在使用:

named_scope :with_suppliers, :include => :suppliers

然后在我看来我正在使用:

and then in my view I'm using:

<%= render :partial => 'category', :collection => @categories.find_all{|c| !c.suppliers.empty? } %>

不完全雄辩,但说明了我正在努力实现的目标.

Not exactly eloquent but illustrates what I'm trying to achieve.

类定义

class SupplierCategory < AR
  has_many :suppliers, :order => "name"
end

class Supplier < AR
  belongs_to :supplier
end

推荐答案

这是另一种方法:

named_scope :with_suppliers, :include    => :suppliers, 
                             :conditions => "suppliers.id IS NOT NULL"

这是有效的,因为 Rails 使用 OUTER JOIN 作为 include 子句.当没有找到匹配的行时,查询返回供应商列的 NULL 值.因此 NOT NULL 检查返回匹配的行.

This works because Rails uses OUTER JOIN for include clause. When no matching rows are found the query returns NULL values for supplier columns. Hence NOT NULL check returns the matching rows.

Rails 4

scope :with_suppliers, { includes(:steps).where("steps.id IS NOT NULL") }

或者使用静态方法:

def self.with_suppliers
  includes(:steps).where("steps.id IS NOT NULL")
end

注意:

该解决方案急切加载供应商.

This solution eager loads suppliers.

categories = SupplierCategory.with_suppliers
categories.first.suppliers #loaded from memory

这篇关于ActiveRecord 查找所有关联孩子的父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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