我有一个具有start_time属性的模型Planning。我想要上午9点到12点或下午6点到11点之间的所有计划。
基本上我会这样做:
Planning.where do
(start_time >= @start_time[0]) & (start_time <= @end_time[0])
|
(start_time >= @start_time[1]) & (start_time <= @end_time[1])
end问题是时隙的数量是不同的..。有什么想法吗?
如果可以的话,我会使用Squeel gem。
提前感谢!
发布于 2012-11-24 18:30:53
您可以在where块中执行任何操作;但是必须在最后返回实际的查询,因为这将用作where子句。
因此,给定一系列这样的时间:
times = [ [ '09:00:00', '12:00:00' ], [ '18:00:00', '23:00:00' ] ]下面是一个详细的解决方案:
Planning.where do
query = nil
times.each do |a,b|
q = (start_time >= a) & (end_time <= b)
if query
query |= q
else
query = q
end
end
query
end这里有一个更聪明的解决方案:
Planning.where do
times.map { |a,b| (start_time >= a) & (end_time <= b) }.reduce(&:|)
end两者都会生成以下SQL:
SELECT "plannings".* FROM "plannings"
WHERE ((
("plannings"."start_time" >= '09:00:00' AND "plannings"."end_time" <= '12:00:00')
OR
("plannings"."start_time" >= '18:00:00' AND "plannings"."end_time" <= '23:00:00')
))发布于 2012-11-23 16:50:07
您可以复制并粘贴ruby代码生成的SQL吗?
编辑
好了,现在我明白你的问题了,问题还不清楚。如果你想保持代码的可读性,在这种情况下你应该使用ARel而不是squeel (至少不是为此而设计的DSL )。您应该能够应用一个map函数,然后使用OR连接所有内容。
发布于 2012-11-23 16:31:26
Squeel where()方法返回的是AR:Relation,不是吗?
然后,您应该能够链接where()调用:
finder = Planing.scoped
time_slots.each do |start_time, end_time|
finder = finder.where{(start_time >= my{start_time}) & (start_time <= my{end_time}) }
end我还没有尝试过这段代码,但我看不出它为什么不能工作
编辑:正如您所说的,这将使用AND链接条件,而不是OR
你能试试下面的方法吗?
Planning.where do
time_slots.inject(false) do |memo, time_slot|
memo | (start_time >= time_slot.first) & (start_time <= time_slot.last)
end
end 这对于使用squeel的instance_eval来说可能有点太神奇了,但是可以试一试:)
https://stackoverflow.com/questions/13520733
复制相似问题