Show name instead of HABTM identifier

Excuse me if I am too much beginner, but not one of the other related workers.

I want to show the name of the category to which the links belong, and not the identifier.

Migration is performed here.

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

Category Model

class Category < ActiveRecord::Base
  has_and_belongs_to_many :links
end

Link Model

class Link < ActiveRecord::Base     
 has_and_belongs_to_many :categories
end

And here’s what's in the link controllers by index and show

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

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

<%= link.category.name %>

If it is set <%= link.category_ids %>, it will display identifiers.

+3
source share
1 answer

Try:

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

Source: https://habr.com/ru/post/1785109/


All Articles