3

I'm following the instructions from http://railscasts.com/episodes/382-tagging and building a Tag System from Scratch. Everything are working great but not the tag_cloud helper. It raises database error while searching for tag_counts.

Following scope:

#Picture.rb

class Picture < ActiveRecord::Base

  attr_accessible :description, :title, :tag_list

  has_many :taggings
  has_many :tags, through: :taggings

#Because of the following I'm getting an error from the Posgresql (showed in "Database Error")

  def self.tag_counts 

    Tag.select("tags.*, count(taggings.tag_id) as count").
      joins(:taggings).group("taggings.tag_id")
  end
end

Application_helper.rb

def tag_cloud(tags, classes)
  max = tags.sort_by(&:count).last
  tags.each do |tag|
    index = tag.count.to_f / max.count * (classes.size - 1)
    yield(tag, classes[index.round])
end

Database Error

ActiveRecord::StatementInvalid in Pictures#index

PG::Error: column "tags.id" ​​should appear in the GROUP BY clause or be used in an aggregate function

LINE 1: SELECT tags.*, count(taggings.tag_id) as count FROM "tags" I...

               ^
: SELECT tags.*, count(taggings.tag_id) as count FROM "tags" INNER JOIN "taggings" ON "taggings"."tag_id" = "tags"."id" GROUP BY taggings.tag_id
lulalala
  • 17,572
  • 15
  • 110
  • 169
CelsoDeSa
  • 55
  • 1
  • 6

1 Answers1

1

You should group by tags.id, and/or count taggings.id

Tag.select("tags.*, count(taggings.id) as count").
  joins(:taggings).group("tags.id")

you can't group and aggregate at the same time in a query.

rewritten
  • 16,280
  • 2
  • 47
  • 50
  • It seems to get the job done querying to the database, thanks! (Obrigado -> Português Brasileiro) But it returns a String object to the Helper Method listed above in Application_helper.rb and I rolling into another issue: `**TypeError in Pictures#index**` `String can't be coerced into Float` – CelsoDeSa Oct 10 '12 at 00:57
  • That's a separate question. Put the expected results and the actual results in a new question (or whatever makes sense to isolate the problem), so everyone can have an opportunity to solve it. The database error has gone away, so this question is closed. – rewritten Oct 10 '12 at 09:13
  • 1
    Thanks, its ok! I've got it right this morning. It was about this line `index = tag.count.to_f / max.count * (classes.size - 1)` that should be `max.count.to_i`. So obvious! – CelsoDeSa Oct 10 '12 at 12:15
  • just post a new question on and I have a feel that you can help. Thanks! – CelsoDeSa Oct 10 '12 at 13:25