undefined method `save' for nil:NilClass

Antarr Byrd picture Antarr Byrd · Jan 18, 2011 · Viewed 8.5k times · Source

I get this error when trying to register a new user.

NoMethodError (undefined method save' for nil:NilClass): app/controllers/users_controller.rb:49:increate' app/controllers/users_controller.rb:48:in `create'

class UsersController < ApplicationController
  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => [:show, :edit, :update]

  #filter_resource_access

  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  def show

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end

  def new
    #@user = User.new
    @carriers = Carrier.find(:all)
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  def edit

  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "Account registered!"
      redirect_back_or_default account_url
    else
      render :action => :new
    end
  end

  def profile
    @user = User.find(params[:id])
  end

  def update

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy
    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end

  def delete
    @user = User.find(params[:user_id])
    @user.destroy
    redirect_to :users
  end

end

Answer

Jed Schneider picture Jed Schneider · Jan 18, 2011

without seeing your view code, its hard to say, but since you have commented out the @user object that is sent to the new view, perhaps the params coming back from the view are not defined as key value pairs from the form as user attributes?