简体   繁体   中英

Undefined method 'errors' for nil:NilClass

I'm following this tutorial on authentication in rails and I'm encountering an issue on the html signup form :

undefined method errors for nil:NilClass

to this line : <% if @user.errors.any? %> <% if @user.errors.any? %> .

I searched a lot on internet and tried a lot of things, but I cannot make it work.

Here is my view :

<%= 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 %>

My controller :

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

and my route :

Rails.application.routes.draw do

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

  resources :users do
    post :create
  end

You need to rename the new action to signup . In current state - rails sees the template for signup and assumes that corresponding controller action is just empty, thus the nil in instance variable, because new is not being called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM