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" %>
<%= 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