我有一个Rails的named_scope,它使用一个条件从表中抽取一周中的特定日子,如下所示:
:conditions => [ 'EXTRACT(DOW FROM bookdate) IN (?)', (1..6).to_a ]1。6日期范围将是一个变量,具体取决于用户想要的日期,
哪个产生这个SQL
(EXTRACT(DOW FROM bookdate) IN (1,2,3,4,5,6)我的问题是,一周的日子不是一个简单的范围...即1..6工作正常(周一...周六),但说6..2将无法正常工作(周六 - 周二)...无论是作为红宝石范围还是需要6,7,1,2而不是6,5,4,3,2(假设6..2在红宝石中工作,它没有)。
我怎样才能创建一个适合这样的日期范围的星期几的自定义范围?
有任何想法吗?
谢谢,
I have a Rails named_scope which is using a condition to pull specific days of the week from the table like so:
:conditions => [ 'EXTRACT(DOW FROM bookdate) IN (?)', (1..6).to_a ]The 1..6 date range will be a variable depending on the dates the user wants,
Which produces this SQL
(EXTRACT(DOW FROM bookdate) IN (1,2,3,4,5,6)My problem is that the days of the week are not a simple range... ie 1..6 works fine (Mon...Sat), but say 6..2 will not work correctly (Sat-Tues)... either as a ruby range or as it would need to be 6,7,1,2 and not 6,5,4,3,2 (assuming 6..2 worked in ruby, which it doesn't).
How can I create a custom range for days of the week that would accommodate a date range like this?
Any ideas?
Thanks,
最满意答案
如果你想要一个函数来生成包含在以下内容中的值的范围:conditions适用于Sat-Tues和Mon-Sat等范围的:conditions如何:
def day_range(from, to) if from <= to (from..to).to_a else (from..7).to_a + (1..to).to_a end end例如
irb(main):032:0> day_range(1, 6) => [1, 2, 3, 4, 5, 6] irb(main):033:0> day_range(6, 2) => [6, 7, 1, 2]然后,如果需要,这只是将日期名称映射到日期数字的情况。
If you want a function to generate the range of values for inclusion in :conditions that will work for ranges like Sat-Tues as well as Mon-Sat how about:
def day_range(from, to) if from <= to (from..to).to_a else (from..7).to_a + (1..to).to_a end ende.g.
irb(main):032:0> day_range(1, 6) => [1, 2, 3, 4, 5, 6] irb(main):033:0> day_range(6, 2) => [6, 7, 1, 2]Then it is just a case of mapping the day names to the day numbers if required.
更多推荐
发布评论