sql - How to Group by Date on Postgres via a Rails Model -
i'm using postgres ruby on rails , query posts table in away returns posts grouped day created_at, each group in chronological order.
a perfect example of goal blog that's index lists posts date.
the pseudo-code object structure expect similar this:
posts_grouped_by_date = { "1/2/2014" => [post1, post2, post3], "1/15/2014" => [post5, post6,post7], etc.. } my table called posts , looks this:
id | title | created_at ----+-------------------------------------------------------------------+---------------------------- 13 | eaque hic tenetur @ quam quibusdam eveniet veritatis. | 2014-08-18 02:40:31.329665 9 | thing want say. | 2014-08-18 02:40:31.329665 16 | est sunt cumque rerum nam nobis consequuntur aut. | 2014-08-19 02:58:26.817936 18 | fuga assumenda facilis aut mollitia eum soluta. | 2014-08-19 02:58:26.837839 8 | thing want say. | 2014-08-18 02:40:31.329665 12 | laudantium dolores odit sed veritatis in et vel deserunt. | 2014-08-18 02:40:31.329665 10 | thing want say. | 2014-08-18 02:40:31.329665 20 | rem laboriosam ipsam sunt maxime quia adipisci et voluptatem. | 2014-08-19 02:58:26.837839 19 | laudantium sit explicabo et quia eligendi ipsam. | 2014-08-19 02:58:26.837839 21 | repellat qui eos dolorem. | 2014-08-19 02:58:26.837839 6 | thing want say. | 2014-08-18 02:40:31.329665 17 | error voluptatem architecto distinctio impedit iste dolores enim. | 2014-08-19 02:58:26.829968 15 | vero modi voluptate deleniti labore quis est. | 2014-08-19 02:58:26.808126 14 | et neque porro qui animi facilis numquam. | 2014-08-19 02:58:26.800474 how using activerecord or arel syntax? explanation behind code helpful too. i'm using learning/practice rather looking copy/paste.
i think want this:
post.order(:created_at).group_by {|p| p.created_at.to_date} 1 - post.order(:created_at) orders posts created_at attribute in ascending order.
2 - then, once have posts ordered group them using code in block. since don't want timestamp included in grouping (each second have different record, what's point?), convert timestamp date.
Comments
Post a Comment