2011-07-16 146 views
0

来源:评论的has_many则返回0空计数

评论:的has_many training_comments

@negative_comments = Source.joins(:comments => [:training_comments]).where("training_comments.category_id = ? and comments.spam = ?", 2, false).select("sources.*, count(comments.id) as ncount").group("comments.source_id") 

我想列出的来源与他们的负面评论数,但我失去它没有negative_comments(training_entries来源.category_id = 2)。我尝试了一切来实现这一点。我尝试了左连接,我试过ifnull但没有一个工作。任何帮助真的非常感激..

我想要做的

源计数

来源1 5

源2 0

source3 13

什么,我得到的是

源计数

来源1 5

source3 13

源表

id: integer 
name: string 

评论表

id: integer 
source_id: integer 
spam: boolean 

Training_comments表

id: integer 
comment_id: integer 
category_id: integer 
+0

这将有助于了解您的数据库结构。 – feeela

+0

我更新了问题 – rOrman

回答

0

你得到一个零,因为标准JOIN当没有比赛不会产生任何东西。你需要得到一个LEFT OUTER JOIN过去的ActiveRecord;这样的事情:

joins('LEFT OUTER JOIN comments ON comments.source_id = sources.id') 

AFAIK,你必须下拉到SQL来获得一个左外部连接。

+0

有没有办法连接3个表 – rOrman

+0

@rOrman:你可以添加另一个'joins'调用('.joins(:third_table)')或者添加更多的SQL到上面的'joins'调用('.joins ('LEFT OUTER ... JOIN third_table ON ...')')。 –

+0

结果仍然相同:( – rOrman