在 has_many 视图表中显示名称而不是 ID

问题描述:

我已经尝试了其他几个类似的帖子,但仍然出现错误.

I have tried a couple other similar posts but am still getting an error.

在 Posts 模型中,我有一个 category_id 字段.我有以下型号:

In the Posts model I have a category_id field. I have the following models:

#Posts model
belongs_to :categories  

#Category model
has_many :posts

在我的帖子索引控制器中:

In the Posts index controller I have:

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

在我的视图中:

<% @posts.each do |post| %>
<tr>
<td><%= post.category_id %></td>
<td><%= @categories.categoryname %></td>

<td><%= link_to 'View', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
</tr>
<% end %>

在第二列中,我试图显示类别表中的类别名称(类别名称"),而不是帖子表中的 category_id.我收到一个错误:

In the 2nd column I am trying to show the category name ("categoryname") from the Category table instead of the category_id from the posts table. I am getting an error:

#ActiveRecord::Relation:0x3e1a9b0 的未定义方法`Category'>

undefined method `Category' for #ActiveRecord::Relation:0x3e1a9b0>

我也试过:

<td><%= post.categories.categoryname %></td>

但得到同样的错误.

还有:

<td><%= post.category.categoryname %></td>

任何建议将不胜感激.

在你的模型中

belongs_to :category

在你看来

<td><%= post.category.categoryname %></td>

您可以去掉控制器中的 @categories =

You can get rid of the @categories = line in your controller

此外,类别名称可能不是您的类别模型的最佳属性名称.为什么不直接将其命名为 name.post.category.name 似乎比 post.category.categoryname 好很多,你不觉得吗?

Also, categoryname is probably not the best attribute name for your Category model. Why not just name it name. post.category.name seems a lot better than post.category.categoryname, don't you think?