所以我的3.2代码看起来像这样
AssocGenre.includes(:genre).where(attachable_type: Project).count(group: 'genres.name').sort_by{|k,v| -v}.each do
但现在它给了我这个错误
undefined method `sort_by' for 193:Fixnum
rails 4.1中的正确语法是什么?
答案 0 :(得分:2)
您曾经能够在调用count
时指定GROUP BY子句,但现在不再能够。现在,您必须通过单独的group
调用指定GROUP BY。来自fine manual:
计数(column_name = nil,options = {})
统计记录 [...]
如果count
与group
一起使用,则会返回一个哈希,其键代表聚合列,值是相应的金额:Person.group(:city).count # => { 'Rome' => 5, 'Paris' => 3 }
您可能希望在SQL中包含一个简单的INNER JOIN而不是includes
添加的所有额外内容,以便joins
更好地工作。
所以你现在想用这种方式写它:
AssocGenre.joins(:genre)
.where(attachable_type: Project)
.group('genres.name')
.count
.sort_by ...
答案 1 :(得分:1)
试一试:
AssocGenre.includes(:genre).where(attachable_type: Project).count(group:'genres.name').**to_a**.sort_by{|k,v| -v}.each.....