Category Listing

Hi there.

I’m relatively new to Ruby on Rails, although not to programming in

I’m attempting to make a sort of classified ad system. I’d like to
have a list of my categories with the number of ads in that category
next to it. For example:

Jobs - Carpenters (1)
Jobs - Electricians (10)
Jobs - IT (3)


I’ve created model, Category, and I’ve linked it to the Classifieds
model, using belongs_to: and has_many: tags.

My problem is that I’ve listed the categories and counts successfully,
but they’re repeating. Instead of the above, it looks more like this:

Jobs - Carpenters (1)
Jobs - Electricians (10)
Jobs - IT (3)
Jobs - Electricians (10)
Jobs - Electricians (10)
Jobs - IT (3)

It’s repeating because I’ve got the loop running in category.rb which
is called from the category_list.html.

Here’s the code from category.rb:

def self.count_categories
count(:id, :conditions => {:category_id => i})

My question is, how can I set it to display only the categories and
their counts without repeating?


i think your problem lies in the way you have arranged your relations.
You talk about Classifieds (Advert i assume), Category and Tag. Now
that is 2 namespaces for a single advert. Ie: One advert belongs to
one category and has many tags…

If we leave the tags alone for the time being, and you want a category
object holding many adverts and an advert belonging only to one
category, then you would do something like:


class Category < AR::Base
has_many :adverts


class Advert < AR::Base
belongs_to :category

your adverts table needs a column :category_id, :integer

=== views/categories/index.rhtml

<%- for category in @categories- %>
Jobs - <%=! %> ( <%= category.adverts.size
%> )
<%- end -%>

=== controllers/categories_controller.rb

def index
@categories = Category.find(:all)

that should do it.

For the tags system, you will need to set up a many to many relation
9which can be of 2 types, has_and_belongs_to_many or
has_many :through, check this out if you’re unaware of them )
where an advert has many tags and a tag has many adverts. then you can
do things like:


hope it helped

Thanks, that did exactly what I wanted!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs