Working with topics and categories

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:

Topic1

(id = 1)
  • Category1
  • (topic_id = 1)
  • Category2
  • (topic_id = 1)
  • Category3
  • (topic_id = 1)
  • Category4
(topic_id = 1)

Topic2

(id = 2)
  • Category1
  • (topic_id = 2)
  • Category2
  • (topic_id = 2)
  • Category3
  • (topic_id = 2)
  • Category4
(topic_id = 2)

Topic3

(id = 3)
  • Category1
  • (topic_id = 3)
  • Category2
  • (topic_id = 3)
  • Category3
  • (topic_id = 3)
  • Category4
(topic_id = 3)

… and so on.

How can I do this?

Thanks.

@topic = Topic.find(:all, :include => “categories”) in your controller

then in your view

<% @topic.each do |t| %>

<%= t.name %>

    <% t.categories.each do |c| %>
  • <%= c.name %>
  • <% end %>
<% end %>

adam

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!

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