使用复杂条件查询的Active Record

时间:2018-03-19 10:13:04

标签: ruby-on-rails postgresql activerecord ruby-on-rails-5

说我有一个模特比赛,每个实例都有很多轮次。每轮都有一个属性:start_date。我想从即将开始的轮次中获取数据库(即在我们开始前5天发送警报。

我尝试构建一个Where Active Record查询,以避免循环并在每轮中检查条件,如果当前日期在所描述的窗口内,直到找到匹配项。有类似的东西:

urgent_rounds = Round.none
pool.rounds.each do |round|
  urgent_rounds << round if DateTime.now.in_time_zone('Greenwich') > round.start_date - (60 * 60 * 24 * 5) && DateTime.now.in_time_zone('Greenwich') < round.start_date
end

感觉不对。所以我所知道的有条件的地方可以写成:

pool.rounds.where("attribute > ? and attribute < ?", value,  value)

在我的情况下,第一个属性应该是start_date,但第二个属性当然不能是start_date。实际上,不能是属性,而是修改原始start_date值所产生的值,如:

current_time_n_date = DateTime.now.in_time_zone('Greenwich')
pool.rounds.where("start_date - (60 * 60 * 24 * 5) < ? and start_date > ?", current_time_n_date,  current_time_n_date)

是否可以构建如上所述的Where查询?怎么样?

1 个答案:

答案 0 :(得分:0)

使用BETWEEN解决了@Gabbar建议。代码下方。

pool.rounds.where('start_date BETWEEN ? AND ?', DateTime.now.in_time_zone('Greenwich'), DateTime.now.in_time_zone('Greenwich') + 5.days)