Reputation: 3195
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?
Upvotes: 0
Views: 451
Reputation: 115392
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.
Upvotes: 3
Reputation: 24020
Supposing that a category record has the name field you can do:
t.categories.map(&:name)
Upvotes: 0