Last Updated: February 25, 2016
·
936
· causztic

Split ActiveRecord results based on a condition!

I have this partial which will render the Articles, but I want to render them on a new division based on the month they are created, and display the month in a header.

Something like this:

Picture

Sorting the results based on date will not help that much since I have to still iterate through the entire array yada yada, check the month, include some variables and conditions...too hairy for me.

After messing around with the Ruby API, I found out that I could just do this:

module SomeHelper

  def group_by_month
    @articles = @articles.chunk{|i|i.created_at.strftime("%B, %Y") || nil }
  end

end

This will return an enumerator which you can do this to render the partial:

- group_by_month.each do |a|
  = render "articles", :a => a

Then on the partial, just read the correct parts of the returned array by:

h4
  = a[0]
- a[1].each_with_index do |a, index|
  =# do stuff with your article!

Have fun with chunk :)