【问题标题】:rails 3 iterate through model with date range and group_by dayrails 3 遍历具有日期范围和 group_by 天的模型
【发布时间】:2011-11-06 21:25:01
【问题描述】:

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

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

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

到目前为止,我只将: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

我用:served_from 和:served_until 替换了:date 来处理比一天更频繁的菜肴。但是如何使用Dish.where 查找:served_from 和:served_until 之间的所有菜肴并按cweek.day 分组?

提前致谢

【问题讨论】:

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


    【解决方案1】:

    也许你在创建菜的时候会向数据库中添加多条记录,例如:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多