TuxedoTomson
TuxedoTomson

Reputation: 483

Rails 4.1 upgrade, having trouble with group

So my 3.2 code looks like this

AssocGenre.includes(:genre).where(attachable_type: Project).count(group:   'genres.name').sort_by{|k,v| -v}.each do 

But now it's giving me this error

undefined method `sort_by' for 193:Fixnum

What is the correct syntax for this in rails 4.1 now?

Upvotes: 0

Views: 133

Answers (2)

mu is too short
mu is too short

Reputation: 434635

You used to be able to specify the GROUP BY clause when calling count but not anymore. Now you have to specify the GROUP BY with a separate group call. From the fine manual:

count(column_name = nil, options = {})

Count the records.
[...]
If count is used with group, it returns a Hash whose keys represent the aggregated column, and the values are the respective amounts:

Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }

You probably want to include a simple INNER JOIN in the SQL rather than all the extra stuff that includes adds so joins should work better.

So you want to write it this way now:

AssocGenre.joins(:genre)
          .where(attachable_type: Project)
          .group('genres.name')
          .count
          .sort_by ... 

Upvotes: 2

scottxu
scottxu

Reputation: 933

just have a try :

AssocGenre.includes(:genre).where(attachable_type: Project).count(group:'genres.name').**to_a**.sort_by{|k,v| -v}.each.....

Upvotes: 1

Related Questions