NoMethodError 未定义的方法“名称"为 nil:NilClass [英] NoMethodError undefined method `name' for nil:NilClass

查看:50
本文介绍了NoMethodError 未定义的方法“名称"为 nil:NilClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型帖子和类别.我试图在我的索引和帖子视图中显示每个帖子的类别名称.我正在使用表连接.但问题是虽然在我的显示视图中类别显示正确,但它在索引视图中为 nil:NilClass 给出了 NoMethodError: undefined method `name'.我不明白为什么它显示在我的显示视图中,而不显示在索引视图中.

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

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

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

类别.rb

class Category < ActiveRecord::Base
  has_many :posts
end

推荐答案

您的 @posts 实例变量包含 Post 的实例,无论出于何种原因,它们都没有关联到父 Category.您可以通过在打印类别名称之前检查每个 Post 是否具有关联的 Category 来避免 NilClass 错误:

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

或者,由于与 Category 无关的 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 %>

这篇关于NoMethodError 未定义的方法“名称"为 nil:NilClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆