Skip to main content

Posts

Showing posts from November, 2015

Rails: Grouping the records by group_by method

Many times we come across such situations where we need to group records, like when we want to display grouped messages, email, alerts .etc based on date or time. Here is the simple code which provides a significant use of group_by method.
Controller Part

classMessagesController < ApplicationController
defindex
@message = Message.all

#Retrives all messages and divides into two groups todays messages and other messages
@grouped_messages = @message.group_by{ |t| t.created_at.to_date == DateTime.now.to_date }