【发布时间】:2012-11-15 12:05:40
【问题描述】:
我有一个国家模型,想显示出现次数最多的国家,国家名称保存在“mame”列中,但是国家数据库是预先填充的,关系是一个国家
has_many recipes
和食谱
belongs_to country
目前为止
Country.group('name').order('count_name DESC').limit(1).count('name')
但这行不通,因为表中每个国家/地区都有 1 个?我需要计算使用 country_id 的次数吗?如果是这样,那么语法是什么?会不会是
Recipe.group('country_id').order('count_country_id DESC').limit(1).count('country_id')
或使用连接并选择
Country.joins(:recipes).select('countries.*, count(country_id) as "country_count"').group(:country_id).order(' country_count desc')
欢迎指点
【问题讨论】:
-
请参阅此处以自行构建查询:stackoverflow.com/questions/10957025/…
标签: ruby-on-rails-3 activerecord