Ruby-on-rails – RoR: Devise: After logging in, It redirects to the login page, how to set redicect after login

deviseruby-on-railsruby-on-rails-3

My routes file:

     get "public/index"

  get "public/timeline"

  devise_for :users
  match '/user' => "public#index", :as => :user_root
  namespace :user do
      root :to => "public#index"
  end
  devise_scope :user do
    get "/login" => "devise/sessions#new"
    get "/logout" => "devise/sessions#destroy"
  end

  root :to => 'public#index'

App Controller

Application Controller:
class ApplicationController < ActionController::Base
  protect_from_forgery

  def after_sign_in_path_for(resource)
      stored_location_for(resource) || root_url
  end
end

I want set the redirect to the root URL

I looked at https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in and it didn't seem to work… maybe my routes are wrong?

EDIT:
The problem is with the logging in action.
here is the console output upon submission of login / password:

Started POST "/users/sign_in" for 127.0.0.1 at 2011-10-25 13:31:16 -0400
  Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"NeWp8HyAg5p9kBOG9ff7U/Z34IGgUorEWNk9wGFn8T0=", "user"=>{"login"=>"DerNalia", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Completed   in 20ms
  Processing by Devise::SessionsController#new as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"NeWp8HyAg5p9kBOG9ff7U/Z34IGgUorEWNk9wGFn8T0=", "user"=>{"login"=>"DerNalia", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Rendered devise/shared/_links.erb (2.3ms)
Rendered devise/sessions/new.html.erb within layouts/application (6.1ms)
Rendered devise/menu/_registration_items.html.erb (0.7ms)
Rendered devise/menu/_login_items.html.erb (0.5ms)
Completed 200 OK in 199ms (Views: 20.2ms | ActiveRecord: 0.8ms)

Best Answer

Devise has a redirect hook for after sign in that you can override in your application controller to accomplish this. First you need to set the devise path to nil with:

def stored_location_for(resource)
  nil
end

Then you can assign your redirect like so:

def after_sign_in_path_for(resource)
  #path_to_redirect_to
end

And that's all there is to changing the redirect after loggin a user in.

Edit

I took a more in depth look at your code and found the login issue you were seeing. In you new session page you were having the login text box point to :username instead of :login, so change

<%= f.text_field :username %></div>

to this

<%= f.text_field :login %></div>

and that should then solve your login issue. I also noticed that in your Devise initializer file you were setting authentication keys on both :login and :email. This is not best practice for Devise and it is recommended that you change it to be strictly login.

Related Topic