Ruby 中的简单自定义范围

发布于 2024-08-20 17:28:24 字数 493 浏览 5 评论 0原文

我有一个Rails name_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 在 ruby​​ 中有效,但事实并非如此)。

如何为一周中的几天创建一个自定义范围来容纳这样的日期范围?

有什么想法吗?

谢谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱你一生 2024-08-27 17:28:25

如果您想要一个函数生成包含在 :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
end

e.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文