Forum: Ruby on Rails Group By

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9904f8acaf66a3c1a4b4434676be11cf?d=identicon&s=25 john (Guest)
on 2005-11-14 04:48
(Received via mailing list)
Is there a way to use group by within find without doing find_by_sql?

I am trying to group all post by date... showing the date and then
all the posts by it... then the next date.  Anyone have any code
snippets for this?

Thanks

John Kopanas

--
http://www.soen.info - where software engineering knowledge gets indexed
http://cusec.soen.info - software engineering conference
E37ca8b3eee534fa6781f7ba13743afb?d=identicon&s=25 ryan.wood (Guest)
on 2005-11-14 05:27
(Received via mailing list)
Have you taken a look at the Calculations plugin?

http://techno-weenie.net/blog/code/269/more-on-act...

I haven't used it yet, but it may help you out. Looks really
interesting.

--Ryan
821395fe70906c8290df7f18ac4ac6cf?d=identicon&s=25 technoweenie (Guest)
on 2005-11-14 06:15
(Received via mailing list)
On 11/13/05, Ryan Wood <ryan.wood@gmail.com> wrote:
> Have you taken a look at the Calculations plugin?
>
> http://techno-weenie.net/blog/code/269/more-on-act...
>
> I haven't used it yet, but it may help you out. Looks really interesting.

That probably won't work.  It's mainly for aggregate queries.

Another option is to group them by date yourself:

@posts = Post.find :all

@grouped_posts = @posts.inject({}) do |all_posts, post|
  (all_posts[post.created_at.to_date] ||= []) << post
  all_posts
end

Then in the view:

# sorts chronologically
<% @grouped_posts.keys.sort.each do |date| -%>
  <h2><%=h date.to_s(:long) %></h2>
  <ul>
  <% @grouped_posts[date].each do |post| -%>
    <li><%=h post.title %></li>
  <% end -%>
  </ul>
<% end -%>
--
rick
http://techno-weenie.net
9904f8acaf66a3c1a4b4434676be11cf?d=identicon&s=25 john (Guest)
on 2005-11-15 04:30
(Received via mailing list)
works great! :-)  thanks
This topic is locked and can not be replied to.