0

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?

John Topley
  • 113,588
  • 46
  • 195
  • 237
datisdesign
  • 3,165
  • 8
  • 30
  • 29

3 Answers3

3

To get the names of the categories associated with your first Template instance, you can do:

Template.first.categories.collect(&:name)

—This uses the Symbol#to_proc support that Rails adds. More information in this Railscast.

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • 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 :) – datisdesign Dec 22 '09 at 15:50
0
t.categories.first.name
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 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 Dec 22 '09 at 14:29
  • 1
    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 Dec 22 '09 at 14:39
0

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

t.categories.map(&:name)
khelll
  • 23,590
  • 15
  • 91
  • 109