Rails 3 使用日期范围和 group_by day 迭代模型
我有一个名为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许当您创建菜肴时向数据库添加多个记录,例如:
添加到数据库不是一种方法
,但
它不是那么漂亮的方法,但它是解决方案。
Maybe when you creating dish add to database more than one record, for example:
and add to database is not a
but
It's not so pretty way, but it's solution.