2016-11-06 14 views
1

這兩個查詢如何在Rails 5中合併?活動記錄欄中兩個查詢的融合

Event 
.where(starts_at: date.beginning_of_day..date.end_of_day) 
.where(kind: "opening") 

Event.where("cast(strftime('%w', starts_at) as int) = ?", date.wday) 
.where(kind: "opening") 
.where(weekly_recurring: true) 

我需要在一個查詢中採取所有這些事件的性能。

感謝您的幫助

回答

0

如果你想結果再結合

Event.where(starts_at: date.beginning_of_day..date.end_of_day).where(kind: "opening").where("cast(strftime('%w', starts_at) as int) = ?", date.wday).where(kind: "opening").where(weekly_recurring: true) 

如果你想在一個查詢兩個獨立的結果,我不認爲活動記錄有這樣的方法。

+0

這不是我所需要的:(我需要開放事件,有好的開始日期和結束日期和事件以及美好的一天(演員表(strftime ....)。 – barnab21

0

我總是更容易編寫複雜的查詢,例如直接在SQL中需要的查詢;編寫代碼比試圖將代碼寫入ActiveRecord要快。

在你的情況,我會做這樣的事情:

query = "starts_at between #{date.beginning_of_day} and #{date.end_of_day} 
and kind = 'opening' 
and weekly_recurring = true 
and cast(strftime('%w', starts_at) as int) = #{date.wday}" 

Event.where(query) 

我發現這種方法更容易,更maintanable。