3
votes

I have two models post and category. I'm trying to show the category name for each post in both my index and show view of post. I'm using table join. But the problem is though in my show view the category is showing properly, but its giving a NoMethodError: undefined method `name' for nil:NilClass in the index view. I can't figure out why it's showing in my show view but not in the index view.

index.html.erb

<% @posts.each do |post| %>
  <h2><%= link_to post.title, post %></h2>
  <p>বিভাগঃ <%= post.category.name %></p>
  <p><%= post.body %></p>
  <%= link_to 'দেখুন', post, class: "button tiny" %>&nbsp;
  <%= link_to 'সম্পাদনা', edit_post_path(post), class: "button tiny" %>
<% end %>

show.html.erb

<h2><%= link_to @post.title, @post %></h2>
<h5>বিভাগঃ <%= @post.category.name %></h5>
<p><%= @post.body %></p>

post.rb

class Post < ActiveRecord::Base
  validates_presence_of :title, :body, :category
  has_many :comments
  belongs_to :category
end

category.rb

class Category < ActiveRecord::Base
  has_many :posts
end
1

1 Answers

12
votes

Your @posts instance variable contains instances of Post that, for whatever reason, aren't associated to a parent Category. You can avoid the NilClass error by checking whether each Post has an associated Category before printing the category's name:

<%= post.category.name if post.category %>

Alternatively, since the existence of a Post that isn't associated with a Category is probably undesirable, you may want to wrap the entire block in a conditional that checks for a Category:

<% @posts.each do |post| %>
  <% if post.category %> # Check for parent category
    # Remaining code
  <% end %>
<% end %>