Topic: best way to manage group by request in rails?

Hey all,
I'm doing something like that:

in my controller:

@posts=Post.find(:all,:group=>'created_on')

then in my view:

<% for post in @posts %>
<div id=posts><% 'Posts created on '+post.created_on%>
@currentposts=Post.find_by_created_on(post.created_on)
<% for p in @currentposts %>
<li>p.title</li>
<% end %>
</div>
<% end %>

Any idea how I could get the list of posts that were created on each date without having to do that Post.find query in my view?

thanx in advance

Pat

Re: best way to manage group by request in rails?

Try this:

# controller
@posts = Post.find(:all)

# view
<% @posts.group_by(&:created_on) do |created_on, posts| %>
  <div id="posts">Posts created on <%= created_on %>
    <% for post in posts %>
      ...
    <% end %>
  </div>
<% end %>


Untested.

Railscasts - Free Ruby on Rails Screencasts

Re: best way to manage group by request in rails?

ok thanx a lot, and what if I want to group them by day cause I'm using datetime which also have hours and second. I would like to group them by day only. Any idea?

thanx in advance

Pat

Re: best way to manage group by request in rails?

Hmm, try this:

# controller
@post_days = Post.find(:all).group_by { |p| p.created_on.beginning_of_day }

# view
<% @post_days.each do |day, posts| %>
  ...
<% end %>

Railscasts - Free Ruby on Rails Screencasts