2012-05-16 37 views
23

我有以下幾點:如何在where子句中結合兩個條件?

time_range = (1.month.ago.beginning_of_month..1.month.ago.end_of_month) 

Comment.where(:created_at => time_range).count 

我如何添加到where子句中包含一個聲明:

.where("user_id is not in (?)",[user_ids]). 

我怎樣才能將二者結合起來?感謝

如果你想

回答

56

「AND」 條件查詢,試試這個:

Comment. 
    where(:created_at => time_range). 
    where("user_id is not in (?)",[user_ids]) 

將產生SQL這樣的:select ... where ... AND ...如果希望WEHRE條款比較複雜

,如:where (a AND b) OR (c AND d),你必須自己將條件合併到條款中,例如

Comment.where("(a AND b) OR (c AND d)") 
+0

錯誤w ActiveRecord :: StatementInvalid:PG :: Error:ERROR:語法錯誤在或在「 – AnApprentice

13
User.where(["name = ? and email = ?", "Joe", "[email protected]"]) 

這將是罰款。

+1

」中執行代碼格式並詳細解釋 –