Forum: Ruby on Rails For Loop

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Pete (Guest)
on 2007-07-10 20:39
(Received via mailing list)
Hi there,

I'm working on my first real rails application (meaning not one out of
a book), and I'm not quite sure how to display the results of a
grouped query. This is what I have in my controller:

@s = Story.find_recent_public_stories
@stories = @s.group_by {|story| story.section}

In my for loop, I've tried various combinations of things like, but so far, I haven't had any luck.
@stories.to_xml and @stories.to_yaml works fine, though. Everything
else returns a NoMethodError.

My ultimate goal is to get a list of stories sorted by category.

Brad C. (Guest)
on 2007-07-10 22:00
(Received via mailing list)
Hi Pete,

In your case group_by returns a hash where the keys are sections and
the values are arrays of stories, so you need to do something like

in your controller:
@s = Story.find_recent_public_stories
@story_lookup = @s.group_by{ |story| story.section }

in your view:
<% @story_lookup.each do |section, stories| %>
  <h2><%= %></h2>
  <% for story in stories %>
     ... do something with story ...
  <% end %>
<% end %>

Ryan B. has a Railcast on group_by: <

This topic is locked and can not be replied to.