简体   繁体   中英

Using group_by beginning_of_month, how do I get an event to show again in the next month?

Using Rails 5.0.2

I have a bunch of events, grouped by month that looks like this:


April

Event 1

23 April - 24 April

Event 2

28 April - 22 June


May

Event 3

4 May - 5 May


The problem is, some events go for ages! Eg Event 2 starts 23 April but finishes 22 June.

How would I get the event item to show up again in the next month(s)?

Current working code:

Controller:

@monthly = @events.group_by { |t| t.start_date.beginning_of_month }

Index view:

<% @monthly.sort.each do |month, event| %>
  <h2><%= month.strftime('%B') %></h2>

    <% for event in event %>

      <li><%= event.title %></li>
      <%= event.start_date %>
      <%= event.end_date %>

    <% end %>
<% end %>

Thanks ya'll!

One approach you could take is to first define the list of all months in the range to be displayed, and then associate all events with that month.

You may wish to tweak the code below for your needs - eg if you don't want to show events in the past, or in the next calendar year:

first_start_month = Event.minimum(:start_date).beginning_of_month
last_end_month = Event.maximum(:end_date).beginning_of_month

months = [first_start_date]
while(months.last != last_end_month) do
  months << months.last + 1.month
end

@monthly_events = months.map do |m|
  [m, @events.select { |e| (e.start_date .. e.end_date).include?(m) }]
end.to_h

With this, your view code can remain basically unchanged:

<% @monthly_events.each do |month, events| %>
  <h2><%= month.strftime('%B') %></h2>

    <% events.each do |event| %>

      <li><%= event.title %></li>
      <%= event.start_date %>
      <%= event.end_date %>

    <% end %>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM