Group By


#1

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 K.


http://www.soen.info - where software engineering knowledge gets indexed
http://cusec.soen.info - software engineering conference


#2

Have you taken a look at the Calculations plugin?

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

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

–Ryan


#3

On 11/13/05, Ryan W. removed_email_address@domain.invalid wrote:

Have you taken a look at the Calculations plugin?

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

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| -%>

<%=h date.to_s(:long) %>

    <% @grouped_posts[date].each do |post| -%>
  • <%=h post.title %>
  • <% end -%>
<% end -%> -- rick http://techno-weenie.net

#4

works great! :slight_smile: thanks