Search code examples
ruby-on-railsrubyruby-on-rails-3registration

undefined method `errors' for nil:NilClass - Ruby on Rails


I am totally new in the Ruby on Rails. I have tried to show an message while register. Please check my controller and view code -

users_controller.rb

class UsersController < ApplicationController
  #before_action :set_user, only: [:show, :edit, :update, :destroy, :success]

  def login
    render layout: false
  end
  def register
    render layout: false
    @user = User.new
  end

  def create_register
    @user = User.new(create_user_params)
    #raise @user.inspect
    respond_to do |format|
      if @user.save
        format.html { redirect_to @users, notice: 'Registration was successfully created.' }
        format.json { render :success, status: :created, location: @users }
      else
        format.html { render :register }
        format.json { render json: @ruby_win_source.errors, status: :unprocessable_entity }
      end
    end
  end

  def success
    raise @user.inspect
  end


  private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :username, :email, :password, :image, :dob, :photo, :address)
  end
end

register.html.erb

<%= form_tag(@user) do |f| %>
         <% if @user.errors.any? %>
          <div id="error_explanation">
            <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
            <ul>
              <% @user.errors.full_messages.each do |message| %>
                <li><%= message %></li>
              <% end %>
            </ul>
          </div>
<% end %>

routes.rb

get    'register'   => 'users#register'
post   'register'   => 'users#create_register'

URL - http://localhost:3000/register

While I am loading this page I got this error message -

enter image description here

I searched in google and getting some same issue link. Follow step but my problem still not resolved. Please help me :(


Solution

  • The 2 lines in your register method are reversed. Try this:

    def register
      @user = User.new
      render layout: false
    end