2015-10-22 32 views
1

我需要計算在子查詢中其他表中的行,所以我用這個查詢:Rails的子查詢始終返回零值

follows_sql = Follow.where(followable_type: 'Idea').where('follows.followable_id = ideas.id').select('COUNT(followable_id)').to_sql 

idea = Idea.select("(#{follows_sql}) AS fcnt").includes(:collaborations). 
    where(collaborations: { user_id: 4, owner: true }) 

所以其生產的有效的SQL,但我從構思VAR不能訪問「FCNT的價值。我試圖用不同的方式來做:

idea[0].fcnt # return nil 
idea[0]["fcnt"] # return nil 

但我只能訪問存在於Idea模型中的字段。 如何訪問我的自定義「FCNT」字段? enter image description here

+0

是什麼'的想法[0] .attributes'說,清理你的代碼? –

+0

列表中的所有想法的屬性,它存在於數據庫 – MeetJoeBlack

+0

'型號attributes'哈希包含了相應的結果集的每一行的所有牽強領域。顯然這個選擇在某個時候出現了。嗯... –

回答

1

我想沿着以下的東西應該爲你

idea = Idea.select("ideas.*, COUNT(follows.id) AS fcnt").joins("LEFT OUTER JOIN follows ON follows.followable_id = ideas.id").group("ideas.id") 

ideas.each do |idea| 
    puts idea.fcnt 
    # Should output a number 
end 

請注意,我已經離開了其他包括和WHERE子句工作。首先嚐試解決問題,如果這個查詢解決了,然後添加你的附加子句。

此外,如果你設置你的關係正常,這樣的想法有許多如下,你可以通過執行類似

ideas = Idea.includes(:collaborations).where(collaborations: { user_id: 4, owner: true }) 

ideas.map { |idea| idea.follows.count } 
+0

是的,'includes'似乎把東西吹進了SQL地獄。但是我們必須等待問題的具體描述才能提出解決方案。 –