2012-03-01 90 views
1

在此论坛搜索后,我发现我在这个问题上处于停滞状态。我正在运行rails 3.2.1和ruby 1.9.3Michael Hartl教程v。3.2第7.17章用户中的NoMethodError#new Line 4

我非常密切地关注了Hartl的书,并且在测试和呈现注册页面时遇到了错误。

下面是一些跟踪误差:

undefined method `model_name' for NilClass:Class 

Extracted source (around line #4): 

1: <% provide(:title, 'Sign up') %> 
2: <h1>Sign up</h1> 
3: 
4: <%= form_for(@user) do |f| %> 
5: <div class="field"> 
6:  <%= f.label :name %><br /> 
7:  <%= f.text_field :name %> 

Rails.root: /Users/Brian/Sites/rails/brightspot_1-1 
Application Trace | Framework Trace | Full Trace 

app/views/users/new.html.erb:4:in  
`_app_views_users_new_html_erb___4096651331723577149_70289685515940' 

这里是我的new.html.erb:

<% provide(:title, 'Sign up') %> 
<h1>Sign up</h1> 

<%= form_for(@user) do |f| %> 
    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :email %><br /> 
    <%= f.text_field :email %> 
    </div> 
    <div class="field"> 
    <%= f.label :password %><br /> 
    <%= f.password_field :password %> 
    </div> 
    <div class="field"> 
    <%= f.label :password_confirmation, "Confirmation" %><br /> 
    <%= f.password_field :password_confirmation %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Sign up" %> 
    </div> 
<% end %> 

这里是我的users_controller.rb

class UsersController < ApplicationController 
    def show 
    @user = User.find(params[:id]) 
    end 

    def new 
    @user = User.new 
    end 

    def new 
    end 
end 

的测试失败:

从rspec的

和错误消息:

Failures: 

    1) User pages signup with invalid information should not create a user 
    Failure/Error: before { visit signup_path } 
    ActionView::Template::Error: 
     undefined method `model_name' for NilClass:Class 
    # ./app/views/users/new.html.erb:4:in  
`_app_views_users_new_html_erb___947544063866573638_70125101083220' 
    # ./spec/requests/user_pages_spec.rb:17:in `block (3 levels) in <top (required)>' 

    2) User pages signup with valid information should create a user 
    Failure/Error: before { visit signup_path } 
    ActionView::Template::Error: 
     undefined method `model_name' for NilClass:Class 
    # ./app/views/users/new.html.erb:4:in  
`_app_views_users_new_html_erb___947544063866573638_70125101083220' 
    # ./spec/requests/user_pages_spec.rb:17:in `block (3 levels) in <top (required)>' 

Finished in 0.20414 seconds 
2 examples, 2 failures 

任何帮助,这将非常感激。在此先感谢,布赖恩。

回答

3

当您传递给form_for的@user对象为零时,会发生该错误。如果你看看你的控制器,new方法定义了两次,在第二个定义中它没有实例化一个@user对象。

删除控制器中new方法的第二个(空)定义,应该很好。

+0

工作!谢谢。 – 2012-03-01 03:23:47

+0

如果有效,那么你应该给@wpgreenway正确的答案。 – 2012-04-12 14:22:30

相关问题