Forum: Ruby on Rails Working with topics and categories

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.
F7ebfd3161cbaac11016690de65c6d1f?d=identicon&s=25 Blinchik (Guest)
on 2006-05-28 15:47
Hello guys,

I'm a newbie in RoR and I have a problem. My DB structure is
======================================
topics table : id(int,11)
               name(varchar,255)

categories :   id (int,11)
               topic_id(varchar,255)
               name(varchar,255)
======================================
--Models:--
class Topic < ActiveRecord::Base
  has_many :categories
end
class Category < ActiveRecord::Base
  belongs_to :topic
end

I need page structure like this:
  <h3>Topic1</h3> (id = 1)
<ul><li>Category1</li> (topic_id = 1)
    <li>Category2</li> (topic_id = 1)
    <li>Category3</li> (topic_id = 1)
    <li>Category4</li></ul> (topic_id = 1)
  <h3>Topic2</h3> (id = 2)
<ul><li>Category1</li> (topic_id = 2)
    <li>Category2</li> (topic_id = 2)
    <li>Category3</li> (topic_id = 2)
    <li>Category4</li></ul> (topic_id = 2)
  <h3>Topic3</h3> (id = 3)
<ul><li>Category1</li> (topic_id = 3)
    <li>Category2</li> (topic_id = 3)
    <li>Category3</li> (topic_id = 3)
    <li>Category4</li></ul> (topic_id = 3)

... and so on.

How can I do this?

Thanks.
F15fdc7cb2e911b3808837f2be244add?d=identicon&s=25 Adam Denenberg (Guest)
on 2006-05-28 17:34
(Received via mailing list)
@topic = Topic.find(:all, :include => "categories") in your controller

then in your view

 <% @topic.each do |t| %>
   <h3> <%= t.name %> </h3>
   <ul>
     <% t.categories.each do |c| %>
       <li> <%= c.name %></li>
     <% end %>
   </ul>
 <% end %>

adam
A517db33fcd00f81a1daf8ddcebe8524?d=identicon&s=25 Vladislav Gorodetskiy (blinchik)
on 2006-05-28 17:57
Thanks Adam. Your answer is very helpful.
I have a question again. I have 3 columns, and 9 topics with N cats.

Topic 1    Topic 4    Topic 7
 Cat 1      Cat 1      Cat 1
 Cat 2      Cat 2      Cat 2
 Cat 3      Cat 3      Cat 3
Topic 2    Topic 5    Topic 8
 Cat 1      Cat 1      Cat 1
 Cat 2      Cat 2      Cat 2
 Cat 3      Cat 3      Cat 3
Topic 3    Topic 6    Topic 9
 Cat 1      Cat 1      Cat 1
 Cat 2      Cat 2      Cat 2
 Cat 3      Cat 3      Cat 3

How can I get 1st, 2nd and 3rd; 4th, 5th and 6th4 7th, 8th and 9th
topics from the loop?
Thanks again!
F15fdc7cb2e911b3808837f2be244add?d=identicon&s=25 Adam Denenberg (Guest)
on 2006-05-29 05:45
(Received via mailing list)
well you can use tables and every 3 rows insert a new 1 column table.

Or you can access the topic number order by doing

   t.categories[1] , t.categories[2] and so on instead of
t.categories.each

adam
This topic is locked and can not be replied to.