Rails教程第8.2.3章用户中的NoMethodError #new

时间:2011-09-15 21:14:33

标签: ruby-on-rails

在添加部分app / views / shared / _error_messages.html.erb

后,我在Users#new中收到NoMethodError
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

这是我的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 %>

我花了很多时间试图做到这一点,但我感到陷入困境。任何线索都会有所帮助。谢谢!

2 个答案:

答案 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而不是引发错误。