1

I have a topic that has many sources (sources belongs to topic). Each source has a published_date field. What I want is to query the topic.sources and group them into arrays of objects based published_date.

One way to do this call the topic.sources, then sort them by published_date. Lastly create new array for each date and shove it into the array accordingly.

topic.sources objects (array):

[#<Source id: 12, topic_id: 2, published_date: "2014-11-13">,
 #<Source id: 9, topic_id: 2, published_date: "2014-10-21">
 #<Source id: 8, topic_id: 2, published_date: "2014-10-21">]

This should look like this array of arrays:

[[#<Source id: 9, topic_id: 2, published_date: "2014-10-21">
 #<Source id: 8, topic_id: 2, published_date: "2014-10-21">],
[#<Source id: 12, topic_id: 2, published_date: "2014-11-13">]]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
jmoon90
  • 339
  • 4
  • 17

1 Answers1

2

Try using group_by:

topic.sources.group_by(&:published_date)

You should get a Hash which would look something like this:

{"2014-10-24" => [#<Source id: 9, topic_id: 2, published_date: "2014-10-21">
                  #<Source id: 8, topic_id: 2, published_date: "2014-10-21">],
 "2014-11-13" => [#<Source id: 12, topic_id: 2, published_date: "2014-11-13">]}
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
  • well done sir. That was exactly what I was looking for. Could you explain what the `&` does? I previously tried `topic.sources.group_by(:published_date)` but this didn't work. – jmoon90 Nov 20 '14 at 16:55
  • 1
    The `&:something` is a shorthand for `{ |x| x.something }`. See also http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby – Uri Agassi Nov 20 '14 at 16:58