2011-07-16 145 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