Ordering by a child model count

You can do something like this....

#In the model...
class Farmer < ActiveRecord::Base
  has_many :chicken

  def self.getFarmers_on_chicken_count()
     find (:all, :joins => "INNER JOIN chickens on chickens.farmer_id
= farmers.id", :select => "farmers.*, count(chickens.id)
chickens_count", :group => "chickens.farmer_id HAVING chickens_count <
10")
  end

end

# In the controller

@all_needed_farmers = Farmer.getFarmers_on_chicken_count()

Here, the output will be all the farmers with chickens less than 10.

If you want to pass the parameter "count_limit" instead of 10...

you can override the function as:

@all_needed_farmers = Farmer.getFarmers_on_chicken_count(count_limit)

Regards.

Hi again.

Kiran Soumya wrote:

You can do something like this....

#In the model...
class Farmer < ActiveRecord::Base
has_many :chicken

def self.getFarmers_on_chicken_count()
    find (:all, :joins => "INNER JOIN chickens on chickens.farmer_id
= farmers.id", :select => "farmers.*, count(chickens.id)
chickens_count", :group => "chickens.farmer_id HAVING
chickens_count <
10")
end

end

Thanks for the replies.

This was along the lines of what I was looking for, but I forgot the
most important thing...

Say chickens have a color, simply a string, such as 'red'.

How would I order the farmers by the number of red chickens they have?

Sorry to be such a pain, I should have remembered this the first time
round.

add chickens.colour = 'red', either as a condition or in the join
clause. Note that you won't get back farmers with no chickens, which
may or may not be the right thing (if you do, then you should be using
a left outer join).

Fred