I have tried a couple other similar posts but am still getting an error.
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')
In the View I have:
<% @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 %>
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:
undefined method `Category’ for #ActiveRecord::Relation:0x3e1a9b0>
I have also tried:
<td><%= post.categories.categoryname %></td>
But get the same error.
As well as:
<td><%= post.category.categoryname %></td>
Any suggestions would be greatly appreciated.
In your model
In your view
You can get rid of the
@categories =line in your controllerAlso, categoryname is probably not the best attribute name for your Category model. Why not just name it
name.post.category.nameseems a lot better thanpost.category.categoryname, don’t you think?