For Loop

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.


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

<%= %>

<% for story in stories %> ... do something with story ... <% end %> <% end %>

Ryan B. has a Railcast on group_by: <Ruby on Rails Screencasts - RailsCasts