Many times we come across situations where we need to group records based on date or time but cannot leverage it to a database. Here is the simple example which uses the group_by method to group records by it’s created_at date differentiating today’s messages with other days’ messages.


@message.group_by{ |t| t.created_at.to_date == DateTime.now.to_date }
The above line returns the messages in Ordered Hash with two keys true and false on which the messages which are of today’s date will be values in truekey and others will be values in false.

Now lets group the other messages according to their month.
@grouped_messages[false].group_by{ |t| t.created_at.month }
Above line will provide us the month-wise grouping of the messages. It will create the Ordered Hash with keys as the month numbers and values as the messages according to their month numbers.

Now let’s create the view to display the grouped messages.

We can use rails helper to get the month name Date::MONTHNAMES[ – month_number – ] to get the name of the month in the view.

So by this we achieve the grouping of the messages.

grouping of the messages

You can also use the gem https://github.com/ankane/groupdate to get more functionality.

Thats it!

References

group_by (Enumerable) – APIdock
Edit description

apidock.com

Thank you for reading!

Click here for more details…


At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.

We also specialize in RPA, AI, Python, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!