Forum: Ruby on Rails Grouping a list of links by category

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.
Maarten H. (Guest)
on 2006-04-14 15:30
Hi,

I want to display a list of links grouped by category like this:
Group 1
 Link 1
 Link 2
Group 2
 Link 1
 Link 2

I have this in my controller:
  def index
    @links = Link.find(:all, :order => "category_id")
  end

And this in the view:
   <ul>
    <% for link in @links %>
    <li>
     <a href="<%= link.url %>"><%= link.link %></a>
    </li>
    <% end %>
   </ul>

Can somebody give my some pointers how to achieve this?
Thanks!

Maarten
Kevin M. (Guest)
on 2006-04-14 18:34
(Received via mailing list)
Maarten,

On Fri, Apr 14, 2006 at 01:30:51PM +0200, Maarten H. wrote:

> I want to display a list of links grouped by category like this:
> Group 1
>  Link 1
>  Link 2
> Group 2
>  Link 1
>  Link 2

What a coinsidence.  I just set up a similar link section yesterday.

> Can somebody give my some pointers how to achieve this?  Thanks!

I'm very new to Rails so there it is very likely that there is a better
way
to do this.  But, the way I did it was:

In my Link controller:

    def list
        @categories = LinkCategory.find(:all, :order => 'name')
    end

And in my list.rhtml view something along the lines of:

<% for category in @categories -%>

    <h2><%= h(category.name) %></h2>

    <% for link in category.links -%>

        <p><%= link_to h(link.name), link.url %></p>

    <% end -%>

 <% end -%>




Kevin
http://www.RawFedDogs.net
http://www.WacoAgilityGroup.org
Bruceville, TX
This topic is locked and can not be replied to.