Ruby-on-rails NoMethodError 未定义的方法“名称”为 nil:NilClass

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21101466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:13:49  来源:igfitidea点击:

NoMethodError undefined method `name' for nil:NilClass

ruby-on-railsruby-on-rails-4

提问by Shuvro

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.

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

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

显示.html.erb

<h2><%= link_to @post.title, @post %></h2>
<h5>?????? <%= @post.category.name %></h5>
<p><%= @post.body %></p>

post.rb

后.rb

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

category.rb

类别.rb

class Category < ActiveRecord::Base
  has_many :posts
end

回答by zeantsoi

Your @postsinstance variable contains instances of Postthat, for whatever reason, aren't associated to a parent Category. You can avoid the NilClasserror by checking whether each Posthas an associated Categorybefore printing the category's name:

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

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

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

或者,由于Post与 a 无关的 a 的Category存在可能是不可取的,您可能希望将整个块包装在检查 a 的条件中Category

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