在HABTM关系中显示名称而不是ID

时间:2011-01-13 00:56:01

标签: ruby-on-rails-3

对不起,如果我是初学者太多而不是其他相关答案的工作人员。

我想显示链接所属的类别名称而不是ID。

这是迁移。

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

类别模型

class Category < ActiveRecord::Base
  has_and_belongs_to_many :links
end

链接模型

class Link < ActiveRecord::Base     
 has_and_belongs_to_many :categories
end

这就是索引下的链接控制器和show

中的内容
@categories = Category.find(:all, :order => 'name')

现在这里是索引中的内容,但是我已经尝试了我能找到的每一个排列。

<%= link.category.name %>

如果它放<%= link.category_ids %>,它会显示ids。

1 个答案:

答案 0 :(得分:1)

尝试:

<% link.categories.each do |cat| %>
  <%= cat.name %><br>
<% end %>
相关问题