2011-01-13 84 views
3

对不起,如果我对初学者太过分,但没有其他相关答案工作者。在HABTM关系中显示名称而不是ID

我想显示链接所属的类别名称而不是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 

这里还有什么是在根据指数的链接控制器和显示

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

以下是目前索引中的内容,但是,我已经尝试了我可以找到的所有这些排列。

<%= link.category.name %> 

如果它把<%= link.category_ids %>,它会显示id。

回答

1

尝试:

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

谢谢!有效! – Thomas 2011-01-13 23:21:49

相关问题