I’m receiving NoMethodError in Users#new after adding the partial app/views/shared/_error_messages.html.erb
Showing /Users/gjb/Sites/rails_projects/sample_app/app/views/shared/_error_messages.html.erb where line #1 raised:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.errors
Here’s my app/views/shared/_error_messages.html.erb
<% if @users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %>
prohibited this user from being saved:</h2>
<p>Ther were problems with the following fields:</p>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Here’s my app/views/users/new.html.erb
<h1>Sign up</h1>
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %>
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
I’ve spent a lot of time on this trying to get it right but I’m feeling stuck at this point. Any clue will be helpful. Thanks!
The first line of your partial where you have
<% if @users.errors.any? %>needs to be<% if @user.errors.any? %>. You’ve got plural instead of singular, so you’re using a variable you never set. And instance variables arenilthe first time they’re used instead of raising an error.