1

I'm wondering what a good way is to log a user in immediately after signing up. I don't require e-mail confirmation so there's no reason a user shouldn't expect this to automatically happen.

  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        format.html { redirect_to welcome_url, notice: "Your user: #{@user.name} was successfully created! Please log in!" }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

One problem I'm seeing is that I don't have a route to connect directly to the POST session#create. It looks like I should but there is no specific route

controller :sessions do
   get    'login'  => :new
   post   'login'  => :create
   delete 'logout' => :destroy
   get 'logout' => :destroy
end

yields:

login GET    /login(.:format)                        sessions#new
      POST   /login(.:format)                        sessions#create
logout DELETE /logout(.:format)                       sessions#destroy
       GET    /logout(.:format)                       sessions#destroy

For reference sake, here's my sessions#create method

def create
  user = User.find_by_name(params[:name])
  if user and user.authenticate(params[:password])
    session[:user_id] = user.id

    if session[:return_to]
      redirect_to session[:return_to]
      session[:return_to] = nil
      return
    end
    redirect_to eval("#{user.role}_url")

  else
    redirect_to login_url, alert: "Invalid user/password combination"
  end
end

Can I just hook directly into my session#create route from my user@create controller method as if the user is signing in except for the first time??

Anil
  • 3,899
  • 1
  • 20
  • 28
Ken W
  • 962
  • 4
  • 12
  • 19

1 Answers1

1

You cannot redirect with post method. See redirect_to using POST in rails. So your options are: 1. Access the sessions model and create a record there from the users create method, or 2. (Not recommended) Create a GET access to the sessions#login method. I hope this helps.

Community
  • 1
  • 1
Anil
  • 3,899
  • 1
  • 20
  • 28
  • I have no sessions model though... I rely on session variables which are set through the sessions controller as you can see... would it maintain RESTful state if I access a controller from another controller? – Ken W May 30 '12 at 04:37
  • You could potentially declare the common code as a method in the applications_controller and invoke it from both controllers. – Anil May 30 '12 at 04:52