views:

128

answers:

3

Hi

I have 2 models which have a has_and_belongs_to_many relation:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :templates
end

class Template < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

I want to know how can I get a category name through this relation, for example I find a first template:

t = Template.find(:first)

Then using t.categories will return an object, but I want to have category.name in return, how can I achieve this?

A: 
t.categories.first.name
Jordan
That only gets you the name of the first category associated with the template. I believe the OP wants the name of all the categories.
John Topley
Ah, that was unclear.
Jordan
But he says "I want to get a category name" not category names. I think he may not be understanding the many part of habtm.
MattMcKnight
A: 

Supposing that a category record has the name field you can do:

t.categories.map(&:name)
khelll
whats the different between map and collect methods ?
Datis
they are the same, name aliases only.
khelll
+2  A: 
John Topley
can i create a link for each of these items in this way ?how can i put some space between each item ?thnx for your help :)
Datis
Try this: http://pastie.org/753210
John Topley