ActiveRecord的发现,已经有联系的儿童家长家长、儿童、发现、ActiveRecord

2023-09-08 18:45:02 作者:空心計

我不知道为什么我不知道这一点,我觉得应该是相当简单的。我有两个模型(见下文)。我试图想出一个名为范围SupplierCategory,将发现所有SupplierCategory(S)(包括:供应商)。谁的相关供应商(S)是不是空的。

我尝试了直线上升的加入, named_scope:with_suppliers,:加入=> :供应商这给了我只有与供应商的类别,但它给了我单独列出每个类别,因此,如果一个类有2家供应商,我得到的类别两次返回数组中:

目前我使用的:

  named_scope:with_suppliers,:包括=> :供应商
 

然后在我看来,我使用:

 <%=渲染:部分=> '分类',:集合=> @ categories.find_all {| C | !c.suppliers.empty? }%GT;
 
Java中的at com.jfinal.plugin.activerecord.Db.query错误,怎么解决呀

不完全是口若悬河,但说明了什么我想要实现的。

类定义

 类SupplierCategory< AR
  的has_many:供应商:为了=> 名称
结束

一流的供应商< AR
  belongs_to的:供应商
结束
 

解决方案

下面是多了一个办法:

  named_scope:with_suppliers,:包括=> :供应商,
                             :条件=> suppliers.id IS NOT NULL
 

这工作,因为Rails使用加盟包括条款。如果未找到匹配行查询返回的供应商列NULL值。因此, NOT NULL 检查返回匹配的行。

轨道4

添加一个静态方法:

 高清self.with_suppliers
  包括:(:步)。凡(steps.id IS NOT NULL)
结束
 

注意:

该解决方案渴望负荷供应商。

 类= SupplierCategory.with_suppliers
categories.first.suppliers从内存#loaded
 

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.

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:

Currently I'm using:

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 Definitions

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

class Supplier < AR
  belongs_to :supplier
end

解决方案

Here is one more approach:

named_scope :with_suppliers, :include    => :suppliers, 
                             :conditions => "suppliers.id IS 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

Add a static method:

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

Note:

This solution eager loads suppliers.

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

 
精彩推荐
图片推荐