2014-03-25 199 views
1

我有一個邏輯問題,我一直無法弄清楚。使用「或」在紅寶石軌道

我試圖計數檢查tasks完成。

下在task.rb正常工作:

def self.done 
    where("rating_id is not null").where("taskterm_id is not null").where("esthours is not null").where("estmat is not null").where("estenddate is not null") 
end 

如果任何5個字段爲null,則任務尚未完成。

但是,我也想爲已完成,如果rating_id = 5

所以,我想這算任務:

where(:rating_id => 5) or (where("rating_id is not null").where("taskterm_id is not null").where("esthours is not null").where("estmat is not null").where("estenddate is not null")) 
end 

但是,它沒有將其設置爲若下半年完成的or是真的。

感謝您的幫助!

回答

1

where方法在ActiveRecord關係上定義。每次撥打where都會返回一個新關係,因此您可以再次撥打where

當使用關係結果時,ActiveRecord執行關係對象返回的sql查詢併爲您提供所有結果。因此,通過調用:

where(:rating_id => 5) or ... 

您正在執行的查詢SELECT <your_table_name>.* FROM <your_table_name> WHERE <your_table_name>.rating_id >= 5。這從來不會是虛假的(在最壞的情況下,它會給你一個空陣列),而or右側的任何內容都將被忽略。

請注意,您只想進行單個SQL調用。爲此,您可以用:

where('rating_id => 5 or (rating_id is not null and taskterm_id is not null and esthours is not null and estmat is not null and estenddate is not null)') 

不幸的是早期版本的軌道沒有不很好的支持,並沒有到目前爲止有定製or支持。你可以看看Squeel寶石來提高查詢,以便它不依賴於純SQL:https://github.com/activerecord-hackery/squeel

還有activerecord_any_of 寶石:https://github.com/oelmekki/activerecord_any_of,與您的查詢可以寫成:

any_of(where(rating_id: 5), 
     where.not(rating_id: nil, taksterm_id: nil, esthours: nil, estmat: nil, estendate:nil) 
    ) 
1
where("rating_id = ? OR (rating_id is not null AND taskterm_id is not null AND esthours is not null AND estmat is not null AND estenddate is not null)", 5) 
+0

這工作 - 感謝您的幫助! – Reddirt