How to group dates according to month? Ruby + Mongoid

Asked

Viewed 178 times

-1

I own a class that contains events and their start dates. I need to retrieve all records by grouping them together so that the first days are listed each time. Example:

2014-01-01, 2014-02-01, 2014-03-01, 2014-01-02, 2014-02-02, 2014-03-02, ...

I need these results to set up a calendar structure. Any help is welcome.

Follows the class.

class Headline
  include Mongoid::Document
  include Mongoid::Timestamps

  field :start_date, type: Date
  field :end_date, type: Date

end

2 answers

0

To group and sort ruby objects:

headlines.group_by { |h| h.start_date.day }
  .values
  .map { |hs|
    hs.sort_by { |h| h.start_date }
  }

If the idea is to delegate the responsibility of grouping and sorting to the database query, an approach like this to Mongodb can be useful: https://stackoverflow.com/a/19713564/1512161

0

You can define a scope and from it return the objects ordered by start date, as an example:

Mongoid

MongoID
# Provide the sorting options.
Person.order_by([[:first_name, :asc], [:last_name, :desc]])

or:

scope :start_date, :order => (:start_date, :asc)
  • Thank you, Jean. But my problem is that I have the following structure: https://gist.github.com/derickhoganpimenta/5ec709708d53df51a92c. This is the structure of a calendar, formed from the dates of the events. Each <tr>, represents a single date of each month. So, I have to display something like this: <tr>&#xA; <td>01-01</td>&#xA; <td>01-02</td>&#xA;</tr>&#xA;<tr>&#xA; <td>02-01</td>&#xA; <td>02-02</td>&#xA;</tr> So, the way I thought to solve this problem, is to group the results, always bringing the first dates, then the second dates, and so on from each month. Ideas?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.