Rails has_many,仅查找那些有孩子的人 [英] Rails has_many, find only those with children

查看:63
本文介绍了Rails has_many,仅查找那些有孩子的人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的产品表has_many:registered_products。

My "products" table has_many :registered_products.

我想使用

products.find(:has_registered_products) 

其中仅返回产品在registered_products表中也有一个条目。我该如何实现?

where that will return only the products that also have an entry in the registered_products table. How could I achieve this?

推荐答案

只要您在registered_products表中具有该产品的外键,就可以执行以下操作:

As long as you have a foreign_key for the product in the registered_products table you can do:

has_many :registered_products
named_scope :with_registered_products, :joins => :registered_products

# if you're using rails 3
scope :with_registered_products, joins(:registered_products)

,并且只会返回至少具有一个相关注册产品的产品。

and that will only return products that have at least one associated registered product.

这篇关于Rails has_many,仅查找那些有孩子的人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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