在添加部分app / views / shared / _error_messages.html.erb
后,我在Users#new中收到NoMethodErrorShowing /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
这是我的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 %>
这是我的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 %>
我花了很多时间试图做到这一点,但我感到陷入困境。任何线索都会有所帮助。谢谢!
答案 0 :(得分:2)
在app/views/shared/_error_messages.html.erb
中,替换:
<% if @users.errors.any? %>
使用:
<% if @user.errors.any? %>
确实,@users
变量不存在。
答案 1 :(得分:2)
部分的第一行<% if @users.errors.any? %>
需要<% if @user.errors.any? %>
。你有复数而不是单数,所以你使用的是你从未设定过的变量。实例变量是第一次使用时nil
而不是引发错误。