Uchenna
Uchenna

Reputation: 4089

How to count has_and_belongs_to_many in Rails?

I am working on a simple Rails with the following structure:

    Product
    has_and_belongs_to_many :subscribers

    Subscriber

    has_and_belongs_to_many :products

How can I get all products that has subscribers which is products with subscribers > 0 ?

def self.has_subscribers
   #subscribers > 0
end

Upvotes: 1

Views: 1424

Answers (3)

Ben Fulton
Ben Fulton

Reputation: 3998

Product.where( '(select count(1) from products_subscribers where product_id = products.id > 0)')

Upvotes: 0

Harsh Gupta
Harsh Gupta

Reputation: 4538

def self.has_subscribers
   Product.joins("LEFT JOIN products_subscribers ON products_subscribers.product_id = products.id").where("products_subscribers.product_id IS NOT NULL")
end

HTH

edit: I am not sure, if below will work, but you may try it: def self.has_subscribers Product.joins(:products_subscribers) end Since, joins use INNER JOIN, it should return only those records of products which have a relationship with subscribers in the joining table.

Edit 2: Just joining with joining table may not (in fact should not) work because joining table usually do not have a model.

The above is working for me, except I forgot to GROUP the results.

Product.joins("LEFT JOIN products_subscribers ON products_subscribers.product_id = products.id").where("products_subscribers.product_id IS NOT NULL").group("products.id")

If you are still getting Subscribers, then it is kinda odd. Please post your function and querying code.

Upvotes: 0

Brock90
Brock90

Reputation: 814

well have you tried doing,

@product.subscribers.count > 0

so you can do something like

def has_subscribers?
  subscribers.count > 0 
end

Upvotes: 3

Related Questions