1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NoMethodError undefined method `name' for nil:NilClass

Posted at

NoMethodError undefined method `name' for nil:NilClass

なぜかNoMethodErrorが出た。
データもあって、modelのリレーションも書いてrails cでは、問題なく稼働していたのに、、、

users_controller.rb
class UsersController < ApplicationController
  def index
    @user = User.all
    @group = Group.all
  end
end
index.html.erb
<h1>Users#index</h1>
<p>Find me in app/views/users/index.html.erb</p
<div>
  <% @user.each do |user| %>
    <p>
      <p>name: <%= user.name %></p>
      <p>email: <%= user.email %></p>
      <p>group: <%= user.groups.name %></p>
      <p><%= user.account.name %></p>
    </p>
  <% end %>

index.htmlの<%= user.account.name %>の部分で、エラーが出てました。

自分の場合は、User.allで全てのユーザーを取っていて、accountを持っていないユーザーがいたため、エラーが出てました。

そのため、index.htmlの<%= user.account.name %>の部分を

<%= user.account.name if user.account %>

と、したところ、問題なく稼働しました。

参照
https://stackoverflow.com/questions/21101466/nomethoderror-undefined-method-name-for-nilnilclass

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?