2008-09-24 58 views
2

是否可以使用子元素屬性對查詢進行分組?按子屬性對Activerecord查詢進行分組

Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city') 

不起作用。

但是,我可以使用author.city作爲條件的一部分。

回答

1

如果這就是你使用的是什麼,那麼語法是錯誤的:組參數,它應該是:

Post.find(:all, :include => [ :author, :comments ], :group=>'authors.city') 

確保您:作者和:評論協會是正確的。如果'authors'是實際的表名,那麼在Post模型和Author模型中需要一個'has_one:author'關聯。

協會必須是正確的,太:

class Post < AR:Base 
    belongs_to :author 
    has_many :comments 
end 

class Author < AR:Base 
    has_many :posts 
end 

class Comment < AR:Base 
    belongs_to :post 
end 

和DB模式:

posts 
    id 
    author_id 
authors 
    id 
comments 
    id 
    post_id 

這將讓正確運行查詢,但是,現在得到一個錯誤結果...:在使用include的情況下:group子句似乎不適用。

+0

對不起,我翻譯我從實際問題的問題。你當然是對的。 – sutee 2008-09-24 05:26:23

0

查看日誌文件中生成的查詢 - 通常可以將查詢粘貼到您最喜歡的MySQL工具中以獲取更詳細的錯誤。

實際上,您可能需要提供一個聚合函數來使數據庫正確分組(這發生在MySQL中,而不是語法錯誤)。

0

作者是否應該被複數化?

Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city') 
2

解決的辦法是強制必要的加盟,使ActiveRecord並解決「authors.city」:

Post.find(:all, :include => [ :author, :comments ], :joins=>"INNER JOIN authors ON posts.author_id=authors.id", :group=>'authors.city')