Can't pass arguments to association.count

A Category has many Products

Why can't I pass arguments to the count or size method?

This works fine: category_obj.products.find(:all, :conditions => "price > 20")

Why cant I do the same with .count or .size?

This doesn't work category_obj.products.count(:conditions => "price > 20")

Neither does this category_obj.products.size(:conditions => "price > 20")

Any ideas how I can do this with out doing Products.count(args)?

Try...

category_obj.products.count("price > 20")

I don’t think that really makes sense since count returns an integer. Include includes associated things. AR objects aren’t associated with integers.

From api.rubyonrails.com:

category_obj.products.count(“id”, :conditions => “price > 20”, :include => :whatever)

True. In this situation then can you not use

category_obj.products.find( :all. :include => :whatever, :conditions => blah ).count

The problem I guess is that it instantiates all those AR objects.

The docs for count suggest that you should be able to include other objects. This is listed as a class method though and looks like it’s marked as depricated.

http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html#M000951

Instead you could use calculate

I believe you could use

category_obj.products.calculate( :count, :include => :whatever, :conditions => blah )

But failing that there’s always

count_by_sql

Sorri if this is off track.

The docs for count suggest that you should be able to include other objects. This is listed as a class method though and looks like it’s marked as depricated.

http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html#M000951

I missed that deprecation noticed. Wish it was bold. :slight_smile:

That’s what i get for skimming…

Ok I’ve just had a quick look at this. If this doesn’t work then I’ll have to wait a bit before I can explore it. The calculate method requires a column to be specified.

category_obj.products.calculate( :count, “*”, :include => :whatever, :conditions => “blah” )

I really should read the docs a little better :wink:

The include option is not included in the calculate method. The sql error that I got was due to the included table not being included as a JOIN operation.

Instead you need to use the old school and verbose :join option

So in your case

category_obj.products.calculate( :count, “*”, :join => “LEFT JOIN whatevers ON whatever.product_id”, :conditions => blah )

Sorry But I can’t spend any more time on this at the moment. If it’s still a problem if someone else can step in or it’ll have to wait until I get home.

Cheers

It worked for you then?