2012-10-04 133 views
2

我試圖做這個Railscast在Postgres上使用我的Rails 3.2應用程序進行標記。除了標籤雲功能外,我的工作正在進行。不過,我通過查看基於用戶創建的標籤形成標籤雲來添加圖層。ActiveRecord/PostgreSQL - GROUP BY子句或在聚合函數中使用

我試圖適應/從Railscast修改代碼:

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

但是當我運行它,我得到了PG錯誤:

PG::Error: ERROR: column "tags.id" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: SELECT tags.*, count(taggings.tag_id) a... 

這裏的車型的外觀:

user.rb

has_many :trades 
has_many :taggings, :through => :trades 
has_many :tags, :through => :taggings 

trade.rb

has_many :taggings 
has_many :tags, :through => :taggings 

tagging.rb

belongs_to :tag 
belongs_to :trade 

tag.rb

has_many :taggings 
has_many :trades, through: :taggings 

如果有人可以幫助伸出援助之手修改查詢做一個cou nt用戶的標籤,將不勝感激。謝謝!

+0

'標籤*,COUNT。 (...)是可疑的。 – wildplasser

+0

您是否需要表格「標籤」來完成該查詢? SQL查詢是否通過tag_id從taggings組中選擇tag_id,count(tag_id);'返回正確的數據? –

+0

哦,它需要標籤,因爲tags.name包含實際的標籤字。標記將交易鏈接到標籤。 – yellowreign

回答

3

這是因爲在Rails的投你發送SQLite的是,當你使用Postgres的用作數據庫;所以問題是,像數據庫SQLite的 MySQL的你添加的集團不 BY子句字段,但的Postgres沒有。

所以你兩個選擇

您使用belong_to協會counter_cache選項在標籤模型
  1. 用以下代替包含連接。

    Tagging.includes(:標籤)。選擇( 「taggings.tag_id,計數(taggings.tag_id)作爲計數」)組( 「taggings.tag_id」)

相關問題