[英]Fusion of two queries in active record rails
How could these two queries be merged in Rails 5? 如何在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)
I need to take all these events in one query for performance. 我需要在一个查询中获取所有这些事件以获得性能。
Thanks for the help 谢谢您的帮助
If you want to combine results then 如果你想结合结果那么
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)
If you want two separate results in one query, i dont think active records has such method. 如果你想在一个查询中有两个单独的结果,我不认为活动记录有这样的方法。
I have always easier to write complex queries such as the one you need directly in SQL; 我总是更容易编写复杂的查询,例如你在SQL中直接需要的查询; It will be faster for you to write than trying to shoehorn it into ActiveRecord.
你写的比试图将它变成ActiveRecord更快。
In your case, I would do something like this: 在你的情况下,我会做这样的事情:
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)
I find this approach easier and more maintanable. 我发现这种方法更容易,也更容易管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.