Search code examples
ruby-on-railsrubyruby-on-rails-4devise

Rails 4 - change URL from /user/:id to /:username


I have a controller pages#dashboard that I have set to be the user_root in my routes.rb

devise_for :users, controllers: { registrations: 'registrations' }
devise_scope :user do
  get "/signup" => "devise/registrations#new"
  get "/login" => "devise/sessions#new"
  get "/logout" => "devise/sessions#destroy"
  get "/:id" => "users#dashboard", :as => "user_root", :id => :username
end

I want the URL to be http://my_app.com/current_user_username

I have set the to_param in the user.rb model to:

def to_param
  username
end

This works fine when I have a link such as:

<%= link_to "MY ACCOUNT", user_root_path(current_user) %>

But on initial login, the URL is: http://my_app.com/username (explicitly says 'username') instead of http://my_app.com/current_user_username

I have tried setting my to_param to:

def to_param
  "#{username}"
end    

and have also tried setting my route.rb to:

get "/:id" => "users#dashboard", :as => "user_root", :id => :username, :via => :get

Neither of these have solved the issue.

Environment: Rails 4.2.5, Ruby 2.3.0, Devise gem 3.5.3

Any help would be greatly appreciated.


Solution

  • I solved this by adding this to application_controller.rb

    def after_sign_in_path_for(resource)
      user_root_path(current_user)
    end
    

    ** This is a Devise specific answer.

    Thanks to everyone who took the time to answer :)