【发布时间】:2014-01-13 21:12:52
【问题描述】:
我有两个模特帖子和类别。我正在尝试在我的索引和显示帖子视图中显示每个帖子的类别名称。我正在使用表连接。但问题是虽然在我的显示视图中类别显示正确,但它在索引视图中给出了 NoMethodError: undefined method `name' for nil:NilClass。我不知道为什么它会显示在我的显示视图中而不是索引视图中。
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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4