Thomas
Thomas

Reputation: 231

Show Name instead of ID in a HABTM relationship

Excuse me if I'm being too much of a beginner but none of the other related answers worker.

I want to show the category name that the links belong to instead of the id.

Here's the migration.

class CreateCategoriesLinks < ActiveRecord::Migration
  def self.up
    create_table :categories_links, :id => false do |t|
  t.references :category
  t.references :link
  end
 end

def self.down
  drop_table :categories_links
end

end

The categories model

class Category < ActiveRecord::Base
  has_and_belongs_to_many :links
end

The links model

class Link < ActiveRecord::Base     
 has_and_belongs_to_many :categories
end

And here's what's in the links controller under index and show

@categories = Category.find(:all, :order => 'name')

and here's what's in the index right now but, I've tried every permutation of this that I could find.

<%= link.category.name %>

If it put <%= link.category_ids %>, it'll show the ids.

Upvotes: 3

Views: 747

Answers (1)

noodl
noodl

Reputation: 17408

Try:

<% link.categories.each do |cat| %>
  <%= cat.name %><br>
<% end %>

Upvotes: 1

Related Questions