2012-10-09 28 views
3

我遵循http://railscasts.com/episodes/382-tagging的指示並從頭開始構建標籤系統。一切都很好,但不是tag_cloud幫手。它在搜索tag_counts時會引發數據庫錯誤。從頭開始標記:標籤雲問題

範圍如下:

#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 

數據庫錯誤

的ActiveRecord :: StatementInvalid在圖片#指數

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 

回答

1

你應該用標籤組s.id和/或計數標記.id

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

您無法在查詢中同時進行分組和聚合。

+0

它似乎完成了查詢數據庫的工作,謝謝! (Obrigado - >葡萄牙語巴西陸軍) 但它在Application_helper.rb返回上面列出一個String對象的helper方法和我睜不開了另一個問題: '**類型錯誤中圖片#指數**' '字符串不能被強制轉換爲浮動' – CelsoDeSa

+0

這是一個單獨的問題。將預期結果和實際結果置於一個新問題中(或者將問題隔離開來),這樣每個人都可以有機會解決問題。數據庫錯誤消失了,所以這個問題關閉了。 – rewritten

+1

謝謝,它確定!今天早上我已經明白了。它是關於這行'index = tag.count.to_f/max.count *(classes.size - 1)'應該是'max.count.to_i'。非常明顯! – CelsoDeSa