0

I have a country model and would like to display the country with the most occurrences, country names are held in the column 'mame', however the country db is pre populated and the relationship is a country

has_many recipes 

and recipe

 belongs_to country

So far I have

Country.group('name').order('count_name DESC').limit(1).count('name')

but this will not work will it as there are 1 of every country in the table? Do i need to do a count on the number of times the country_id is used? if so what would the syntax be for that? would it be

Recipe.group('country_id').order('count_country_id DESC').limit(1).count('country_id')

or using joins and select

Country.joins(:recipes).select('countries.*, count(country_id) as "country_count"').group(:country_id).order(' country_count desc')

Any pointers appreciated

Richlewis
  • 15,070
  • 37
  • 122
  • 283
  • See here for constructing the query yourself: http://stackoverflow.com/questions/10957025/rails-3-order-by-count-on-has-many-through – Damien Roche Nov 15 '12 at 12:23

1 Answers1

2

You can do it by using queries. However, RoR has built in support to achieve the same. It is called Counter Cache.

I can explain here but I think it's better if you follow this screencast.

http://railscasts.com/episodes/23-counter-cache-column

This will give you very good idea how to use counter cache and get what you've tried to achieve.

HungryCoder
  • 7,506
  • 1
  • 38
  • 51