I have a model called event_recurrences it contains 2 important columns event_id and cached_schedule
cached_schedule contains an array of dates
event_id is used to reference the event
I need to
-
Get all the event_recurrence objects
@something.event_recurrences– Done -
Go through each recurrence object and get the
event_idand all the
dates fromcached_schedule -
Iterate through each month, and spit out a list like the following
Jan
event_id date
event_id date
event_id date
Feb
event_id date
… and so on
To recap the event_id is located event_recurrence.event_id the dates that the event_id will happen on are located in an array inside event_recurrence.cached_schedule
Some I have some incomplete code to work with…
This code works successfully to show each event_recurrence object by month using the created_at field.
in my controller
@schedule_months = @something.event_recurrences.order("created_at DESC").group_by { |e| e.created_at.beginning_of_month }
in my view
<% @schedule_months.keys.sort.each do |month| %>
<div class="month">
<%= month.strftime("%B %Y") %>
</div>
<% for event in @schedule_months[month] %>
<li><%= event %></li>
<% end %>
<% end %>
Thanks in advance.
Sincerely, jBeas
There are some details missing from your question… for example, can the dates in
cached_schedulespan multiple months, or are they all guaranteed to be in the same month?If you just want to use core Ruby:
Then in the view:
You may have to adjust the code a little depending on the specifics, but this should give you the idea. Note the use of destructuring assignment:
@event_dates[month].each do |(date,event_id)|. This saves a line of code and expresses what the code is doing more clearly.If you don’t mind adding your own extensions to the core Ruby classes, you could make this code even cleaner and more consise. I often use a method which I call
mappend:The name is a mix of
mapandappend— it is likemap, but it expects the return value of the mapping block to also beEnumerable, and it “appends” all the returnedEnumerables into a singleArray. With this, you could write:OK, that might be a lot for one line, but you get the idea: it saves you from using an intermediate variable to accumulate results.
UPDATE: Something like
mappendis now part of the Ruby core library! It’s calledflat_map.