rails 3遍历具有日期范围和group_by天的模型

时间:2011-11-06 21:25:02

标签: ruby iterator group-by ruby-on-rails-3.1 where

我有一个名为Dish的模型,每天:served_from:served_until,例如意大利肉酱面于2011-10-31周一至2011-11-06周日供应。

在餐厅展示页面上,我想展示在cweek 44期间可用的所有菜肴:

  • 星期一:spaghetti bolognese
  • 星期二:spaghetti bolognese
  • ...

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

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

我将:date替换为:served_from:served_until来处理一天中更常服务的菜肴。但是,如何使用Dish.where查找:served_from:served_until之间的所有菜肴,并按cweek.day分组?

提前致谢

1 个答案:

答案 0 :(得分:0)

也许当你创建dish添加到数据库的多个记录时,例如:

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"}]

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