Rails has_many, find only those who have children

My Products table has_many: registered_products.

I want to use something like

products.find(:has_registered_products) 

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

+5
source share
5 answers

As long as you have 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 this will only return products having at least one associated registered product.

+10
source

This will handle duplication.

Product.joins(:registered_products).uniq
+3
source

, , , .

"select different" , select , .

- , , . ,

class Product < ActiveRecord::Base
 has_many registered_products

 scope :with_registered_products, joins('join (select distinct product_id from registered_products) rp123456 on rp123456.product_id = products.id')
end
+1
class Product
  has_many :registered_products
end

( ) -

Product.all(:include => :registered_products, 
  :conditions => "registered_products.id IS NULL")

( ) -

Product.all(:joins => :registered_products)
0

counter_cache (http://railscasts.com/episodes/23-counter-cache-column). , , , .

0

All Articles