I’m building a small app that takes things entered into an input field and displays them directly below that input field when entered.
My goal with this code is to separate those entries by date so that all things posted on June 1 are posted with one line break between them and the first entry of June 2 has 2 spaces between it and the entries from June 1.
This is my code and it’s not acting as planned but I can’t figure out why, I think it stems from line 3 and something I’m doing incorrectly. (Note: I’m aware this doesn’t account for changes in month or year yet. I’ll get to that once I figure out proper date spacing)
<% for i in (0..(@allLessons.count-1)) %>
<b><%= @date[i].created_at.strftime('%b %d')%></b><br/>
<% if @date[i].created_at.strftime('%d') == @date[i-1].created_at.strftime('%d') %>
<%= @date[i].created_at.strftime('%d') %> <br />
<% else %>
<%= @date[i].created_at.strftime('%d') %><br /><br />
<% end %>
<% end %>
From the controller:
@allLessons = Lesson.all
@date = Lesson.find(:all, :order => 'created_at ASC')
Any help you could lend on this would be hugely appreciated!
Blocks and iterators are where it’s at.
Annotated
First we get all of the lessons together. This is equivilant to find(:all, :order => ‘created_at ASC’), but I like this newer, compact syntax
Then we group them all together into a hash where the key is the date and the value is an array of records that were created on that day.
beginning_of_dayconverts aDateTimeinto aDatewhere the time is set to00:00:00. So,2012-05-25 18:00becomes2012-05-25 00:00:00. This is so we can group the dates themselves without the time getting in the way@datesis now a hash where the keys are dates and the values are arrays of lessons from that date. for example,{ '2012-05-24 00:00:00' => [ lesson_1 ], 2012-05-25 00:00:00' => [ lesson_2, lesson_3 ]We then pass the hash into a block, where the key is the date, and the value is the array of lessons. This is saying, for each date…
Give me the lessons that belong to that date. And for each of those…
print out the date of the lesson
before moving on to the next date, print a
<br />