Rails:根据属性对部分进行分组
我有一个使用日历的应用程序,我想在登录时提供日历摘要。摘要的格式应使其显示今天、明天和本周的事件,如下所示:
活动对象:
今天
- 事件 1
明天
- 事件 2
- 事件 3
- 活动 4
本周
- 事件 5
- 事件 6
- 事件 7
- 事件 8
如何渲染部分内容,以便根据日期以正确的方式将它们分组在一起?
I've got an application that uses a calendar, and I'd like to provide a calendar summary on login. The summary should be formatted so it shows events for Today, Tomorrow, and This Week, like this:
Events For:
Today
- Event 1
Tomorrow
- Event 2
- Event 3
- Event 4
This Week
- Event 5
- Event 6
- Event 7
- Event 8
How do I render the partials so that they are grouped together in the right way, based on their date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个可以添加一个模型方法 for_dates(start_date,end_date) ,其中包含:
where([:date_column >= ? and :date_column <= ?, start_date, end_date])
然后使用:
Model.for_dates(Date.today, Date.today)
Model.for_dates(Date.today+1, Date.today+1)
默认“周”是周日到周一。如果您希望不同的日期,请添加偏移量,例如
星期一到星期五是
Model.for_dates(Date.today.beginning_of_week+1, Date.today.end_of_week+1)
First one could add a model method for_dates(start_date,end_date) which would contain:
where([:date_column >= ? and :date_column <= ?, start_date, end_date])
Then use:
Model.for_dates(Date.today, Date.today)
Model.for_dates(Date.today+1, Date.today+1)
Default 'week' is Sunday to Monday. Add an offset if you wish different days, e.g.
Monday to Friday is
Model.for_dates(Date.today.beginning_of_week+1, Date.today.end_of_week+1)
假设您的模型称为
Event
并且它具有date
属性,并且您的这些集合称为@events
,这里有一个想法:将其在你看来......那么你就会有一个名为
_event.html.erb
的部分,如下所示:发生的事情是在我们正在执行的
render
调用中传入整个@events
集合作为本地称为events
。然后在部分内部,我们使用自动生成的event_counter
方法来查找上一个 (events[event_counter - 1]
) 和下一个 (events[event_counter + 1] ]
) 集合中的事件。然后,如果当前事件
的日期与last_event
的日期不同(这意味着它是该日期的第一个事件),我们将开始一个带有新日期标题的新集合,如果event
的日期与next_event
的日期不同(即,它是该日期的最后一个),我们就结束该组。这有点难看,当然还有更优雅的方法可以做到这一点,但它可以完成工作。
Supposing your model is called
Event
and it has adate
attribute, and your collection of these is called@events
, here's one idea: Put this in your view......then you would have a partial called
_event.html.erb
that looks like this:What's happing is in the
render
call we're passing in the whole@events
collection as a local calledevents
. Then inside the partial we use the automatically-generatedevent_counter
method to look up the previous (events[event_counter - 1]
) and next (events[event_counter + 1]
) events in the collection. Then if the date of the currentevent
is different from the date oflast_event
(meaning it's the first one for that date) we start a new set with a new date heading, and if the date ofevent
is different from the date ofnext_event
(i.e. it's the last one for that date) we end the set.It's a little ugly, and there are more elegant ways to do it for sure, but it gets the job done.