2016-06-07 49 views
0
@counseling = Counseling.ransack(params[:q]) 
@counselings = @counseling.result.joins('RIGHT JOIN "subjects" ON "subjects"."id" = "counselings"."subject_id"') 
@result = {} 
@result[:data] = @counselings.group(row_condition).count 

塊引用紅寶石如何強制輸出0時計數沒有行

def self.create_case_sql_for_nested_tree2(foreign_key) 
    modelClass = foreign_key.sub(/_id3$/, '').camelize.constantize 
    @when_then_conditions = modelClass.roots.map do |o| 
     o.children.map do |c| 
     c.children.map do |g| 
     idlist = g.self_and_descendants.pluck(:id) 
     "WHEN subject_id IN(#{idlist.join(',')}) THEN #{g.id}" 
     end 
     end 
    end 
    "CASE #{@when_then_conditions.join(' ')} ELSE null END" 
end 
+0

你能更準確的瞭解您的問題。因爲如果沒有找到行,count通常會返回0。 –

+0

select s.id,count(nullif(subject_id,0))來自counselings的AS計數c right加入對象s on c.subject_id = s.id group by s.id order by s.id; – Poo

+0

當我執行上面的SQL輸出顯示0計數的記錄但我不知道如何在紅寶石中實現相同。 – Poo

回答

2

根據您的意見,您想加入CounselingSubject模型並計算subject_id。我認爲你可以像這樣做,

Counseling.joins(:subject).count(:subject_id) 

如果你想要把任何地方的條件,你可以像這樣做,

Counseling.joins(:subject).where("some condition").count(:subject_id) 
+0

感謝您的回覆。正如你可以在我的sql看到的,我想要在輔助模型的領域subject_id上進行計數,但是希望按主題模型subjectid字段進行分組。這就是爲什麼我使用CASE SQL。 – Poo

+0

問題是我不知道如何做正確的加入。當我們使用連接(:主題)時,它會進行內部連接。我需要計數功能來計算空行。我不認爲在ruby中有任何像nullif這樣的函數來執行該操作..count(:subject_id)將計算所有非空行。 – Poo