Cninroh
Cninroh

Reputation: 1796

Rails - how to get category name out of database?

I have a Product which has a has_and_belongs_to_many relationship with a category. I am using simple_form with Twitter Bootstrap integration, in order to generate Checkboxes, that allow to select multiple Categories per Product.

Unfortunately when I ask Rails for "product.categories", what I get is : "[#]"

How can I access the name of this Category? "product.categories.name" doesnt seem to work.

Upvotes: 0

Views: 75

Answers (2)

Shanky Munjal
Shanky Munjal

Reputation: 671

You will get an array of names of categories of product by this:

product.categories.collect(&:name).to_param

Upvotes: 0

Sachin R
Sachin R

Reputation: 11876

You can get objects of categories

product.categories.each do |category|
  category.name
end

or 

product.categories[0].name #for first category from categories

Upvotes: 1

Related Questions