1
votes

Trying to learn ruby on rails following Michael Hartl's tutorial, when I try to go to the registration page in the book I get this:

NoMethodError in UserController#register undefined method `save' for nil:NilClass

here is the code from the user_controller.rb file:

   class UserController < ApplicationController
    def index
     @title = "RailsSpace User Hub"
     end

     def register
     @title = "Register"
     if request.post? and params[:user]
    @user = User.new(user_params)
    end
    if @user.save
    flash[:notice] = "User #{@user.screen_name} created!"
    redirect_to :action => "index"
   end
  end

  private

  def user_params
  # Add the user attributes that you sent with post (form) to the permit 
   method.
  params.require(:user).permit(:name, :screen_name)
  end
end

It's complaining about line 11 where it says: if @user.save I'm just following the tutorial I don't know what's going on.

2

2 Answers

2
votes

Try to understand what the error message is saying. You're trying to call .save on @user but where you are calling it, @user may not be defined. The problem is you can't call .save on a nil object so it throws NoMethodError.

You're logic is incorrect so you must first make sure @user is instantiating a new User instance. It should be more like this:

def register
  @title = "Register"
  if request.post? && params[:user]
    @user = User.new(user_params)
    if @user.save
      flash[:notice] = "User #{@user.screen_name} created!"
      redirect_to :action => "index"
    else
      # handle erorrs here
      flash[:alert] = "Please fix errors: #{@user.errors.full_messages.inspect}"
      redirect_to :back #this may need to change depending, just an example.
    end
  end
end
0
votes

NoMethodError in UserController#register undefined method 'save' for nil:NilClass

The error is thrown because you are calling save on a nil; and it is because nil object does not have this method. the save is a instance method belonging to ActiveRecord::Base class.

The reason @user is nil is because @user is an instance variable in the UserController class which you have not given it any value. Any variable starting with @ inside a class is an instance variable in Ruby.

To solve this problem, you should set a value to @user, and in this case it should be a User instance. You can either create a new user object by doing @user = User.new(user_params) or you fetch a record from the Database by doing @user = User.find(<some_id>)