0

I have a DataMapper::Collection Object. Each of it's entries has a created_at property. I want to render the entries into html tables, one table per day (I use Sinatra for that).

It was no problem to render everything into one table, but I didn't get it to do so for every day. I thought of an array of DataMapper::Collection objects over which I would just iterate and do the job. But I don't know how to build such an array :/

Does anyone know how to solve my problem, or does anyone have a different/better approach? Thanks in advance!

le_me
  • 3,089
  • 3
  • 26
  • 28
  • Old question I know, but one option is to use `Model.all.group_by &:created_at` which will then be a Hash with the dates as keys and Arrays as values. – morbusg Apr 11 '13 at 10:56
  • This is great! sorry for the probably dumb question, but what does the ampersand do here? – le_me May 14 '13 at 15:55
  • Here it's [`Symbol#to_proc`](http://ruby-doc.org/core-1.9.3/Symbol.html#method-i-to_proc). – morbusg May 14 '13 at 16:39
  • ok thank you! do you also have a solution for grouping the records by two columns? – le_me May 14 '13 at 17:08
  • Sure: one way is to `Model.all.group_by {|m| [m.something, m.something_else] }`, which will then be an array of arrays with both "keys" and "values" being arrays. – morbusg May 15 '13 at 06:07

1 Answers1

1

You have (at least) two options. The first is to let the database do the work for you. I don't know about datamapper but most database mappers (!) have functionality to group using SQL's GROUP BY. In this case you would have to use a database function to get the date out of the timestamp and then group on that. This is the fastest option and if you and future maintainers are familiar with relational databases probably also the best.

The second option is to to the mapping in your code. I can't come up with an elegant Ruby thing right now but you could at least do:

mapped_result = Hash.new [] # initiates each new entry with empty array
mapper_collection.each do |one_record|
  mapped_result[one_record.created_at.strftime '%Y-%m-%d'] << one_record
end

and then you can get to record for a day with

mapped_result['2012-11-19']
froderik
  • 4,642
  • 3
  • 33
  • 43