Rails 3 使用日期范围和 group_by day 迭代模型

发布于 2024-12-13 18:02:35 字数 892 浏览 1 评论 0原文

我有一个名为 Dish 的模型,每天 :served_from:served_until,例如意大利肉酱面从 2011 年 10 月 31 日星期一供应到星期日 2011 年 11 月 6 日。

在餐厅显示页面上,我想显示第 44 周期间提供的所有菜肴:

  • 星期一:意大利肉酱面
  • 星期二:意大利肉酱面
  • ...

到目前为止,我只将 :date 存储在 Dish 中并使用以下代码按天对当前周的所有菜肴进行分组:

dishes = Dish.where(:date => (Date.commercial(Date.today.year, Date.today.cweek, 1))..(Date.commercial(Date.today.year, Date.today.cweek, 7)))
dishes.group_by(&:date).each do |date, dish|
  puts "Date: #{date}"
  puts "Dishes: #{dish.count}"
  dish.each do |dish|
    puts dish.name
  end
end

我用 :served_from:served_until 替换 :date 来处理菜肴哪些是服务次数超过一天。但如何使用 Dish.where 查找 :served_from:served_until 之间的所有菜肴并按 cweek.day 将它们分组?

提前致谢

I have a model called Dish which is :served_from and :served_until a day, e.g. spaghetti bolognese is served from Monday 2011-10-31 until Sunday 2011-11-06.

On the restaurant show page I want to display all dishes available during cweek 44:

  • Monday: spaghetti bolognese
  • Tuesday: spaghetti bolognese
  • ...

Until now I only stored :date in Dish and used the following code to group all dishes of the current cweek by day:

dishes = Dish.where(:date => (Date.commercial(Date.today.year, Date.today.cweek, 1))..(Date.commercial(Date.today.year, Date.today.cweek, 7)))
dishes.group_by(&:date).each do |date, dish|
  puts "Date: #{date}"
  puts "Dishes: #{dish.count}"
  dish.each do |dish|
    puts dish.name
  end
end

I replaced :date with :served_from and :served_until to handle dishes which are served more often then one day. But how do I use Dish.where to find all dishes between :served_from and :served_until and group them by cweek.day?

Thanks in advance

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

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

发布评论

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

评论(1

始终不够爱げ你 2024-12-20 18:02:35

也许当您创建菜肴时向数据库添加多个记录,例如:

title: spaghetti bolognese
served_from: 2011-10-29
served_until: 2011-10-31

添加到数据库不是一种方法

{title: "spaghetti bolognese", served_from: "2011-10-29", served_from: "2011-10-31"}

,但

[{title: "spaghetti bolognese", date: "2011-10-29"}, {title: "spaghetti bolognese", date: "2011-10-30"},{title: "spaghetti bolognese", date: "2011-10-31"}]

它不是那么漂亮的方法,但它是解决方案。

Maybe when you creating dish add to database more than one record, for example:

title: spaghetti bolognese
served_from: 2011-10-29
served_until: 2011-10-31

and add to database is not a

{title: "spaghetti bolognese", served_from: "2011-10-29", served_from: "2011-10-31"}

but

[{title: "spaghetti bolognese", date: "2011-10-29"}, {title: "spaghetti bolognese", date: "2011-10-30"},{title: "spaghetti bolognese", date: "2011-10-31"}]

It's not so pretty way, but it's solution.

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