Show name instead of ID in has_many lookup table

I tried a couple of other similar messages, but I still get the error message.

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

#Posts model
belongs_to :categories  

#Category model
has_many :posts

The message index controller has:

@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 second column, I'm trying to show the category name ("categoryname") from the Category table, not the category_id from the posts table. I get an error message:

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

I 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.

+3
source share
5 answers

In your model

belongs_to :category

In your opinion

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

@categories =

, categoryname, , . name. post.category.name , post.category.categoryname, ?

+11

,

belongs_to :categories  

_to .

belongs_to :category 

category_id .

@post.category.categoryname

,

#Post
has_and_belongs_to_many :categories

#Category
has_and_belongs_to_many :posts

categories_posts category_id post_id, ,

@post.categories.each do |cat|
  cat.categoryname
end

,

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

- , , , , , .

+4

:

undefined `categoryname ' nil: NilClass : <% = post.category.categoryname% >

.

, ,

+1

i , @category c, , , ""!

0

, , category_id ( ),

if post.category_id?

:

<td><%= post.category.categoryname if post.category_id? %></td>

post.category_id null, .

0

All Articles