nil的未定义方法'errors':NilClass

时间:2016-02-08 16:42:21

标签: ruby-on-rails ruby

我正在关注this tutorial on authentication in rails并且我在html注册表单上遇到问题:

  

errors

的未定义方法nil:NilClass

到这一行:<% if @user.errors.any? %>

我在互联网上搜索了很多东西并尝试了很多东西,但我无法让它发挥作用。

以下是我的观点:

<%= form_for(:user, :url => {:controller => 'users', :action => 'create'}) do |f| %>
  <input class="col-lg-4 col-lg-offset-4" type="text" placeholder="Email" size="6"></br>
  <input class="col-lg-4 col-lg-offset-4" type="password" placeholder="Password" size="6"></br>
  <input class="col-lg-4 col-lg-offset-4" type="password" placeholder="Password confirmation" size="6"></br>
  <%= f.submit %><div id="valid"><input class="col-lg-4 col-lg-offset-4" type="submit" value="Sign up"/></div>
  <button type="button" class="btn btn-link col-lg-4 col-lg-offset-4"><%=link_to "Already registered ?", home_path%></button>
<% end %>
<% if @user.errors.any? %> // The error line 
  <ul class="Signup_Errors">
  <% for message_error in @user.errors.full_messages %>
    <li>* <%= message_error %></li>
  <% end %>
  </ul>
<% end %>

我的控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "You signed up successfully"
      flash[:color]= "valid"
    else
      flash[:notice] = "Form is invalid"
      flash[:color]= "invalid"
    end
    render "new"
  end
end

和我的路线:

Rails.application.routes.draw do

  root :to => 'users#home'
  get 'home' => 'users#home'
  get 'signup' => 'users#signup'

  resources :users do
    post :create
  end

1 个答案:

答案 0 :(得分:2)

您需要将new操作重命名为signup。 在当前状态 - rails看到signup的模板并假设相应的控制器操作只是空的,因此实例变量中的nil,因为new未被调用。