Question

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
Was it helpful?

Solution

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?

OTHER TIPS

The error is happening because the @user variable is nil, so calling (nil).save will fail. This means that User.new(params[:user]) is returning nil, which should never happen. User.new should always return a record, even if it is invalid.

So, since the controller looks pretty ordinary, I'll take a shot in the dark and suggest checking your User model for a 'new' method. You might be overriding ActiveRecord's 'new' method with some logic that returns nil and breaks your controller. If so, you must replace 'def new' with a different method name.

If that doesn't help, please provide us with the code in your User model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top