簡體   English   中英

在活動記錄欄中融合兩個查詢

[英]Fusion of two queries in active record rails

如何在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)

我需要在一個查詢中獲取所有這些事件以獲得性能。

謝謝您的幫助

如果你想結合結果那么

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)

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

我總是更容易編寫復雜的查詢,例如你在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)

我發現這種方法更容易,也更容易管理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM