Rails has_many,只查找有孩子的
我的“产品”表 has_many :registered_products。
我想使用类似于
products.find(:has_registered_products)
where 的方法,仅返回在 Registered_products 表中也有条目的产品。我怎样才能做到这一点?
My "products" table has_many :registered_products.
I want to use something like
products.find(:has_registered_products)
where that will return only the products that also have an entry in the registered_products table. How could I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只要您在注册产品表中有该产品的外键,您就可以执行以下操作:
并且这只会返回至少具有一个关联注册产品的产品。
As long as you have a foreign_key for the product in the registered_products table you can do:
and that will only return products that have at least one associated registered product.
这将处理重复。
This will handle the duplication.
正如 Jakob 指出的,如果有多个子记录,您需要确保不会返回多个父对象。
使用“select unique”是可行的,但是当此作用域与其他作用域组合时,select 语句可能会产生干扰。
另一种选择是确保您连接到仅具有唯一记录的子表。您可以通过如下方式编写联接来完成此操作
As Jakob points out, if there are multiple child records, you need to ensure that you are not returning multiple parent objects.
Using the "select distinct" will work, but the select statement could interfere when this scope is combined with other scopes.
Another option is to ensure that you join to a child table that only has unique records. You can do this by composing your join as follows
产品列表(至少有一个注册产品) - 急切加载的注册产品
产品列表(至少有一个注册产品) - 没有急切加载
List of Products (with at-least one registered product) - Eager loaded registered products
List of Products (with at-least one registered product) - Without eager loading
您可以使用 counter_cache (http://railscasts.com/episodes/23-counter-cache-column)。它应该比仅仅为了查明是否有子节点而实际进行连接要快。
You could use counter_cache (http://railscasts.com/episodes/23-counter-cache-column). It should be faster than actually doing the join just to find out if there are any children.