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

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.

You can simply add another route above everything in your routes.rb as:
get "/:username" => "users#dashboard", :as => "user_root"
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
Then you need to find the user by something like this:
#user = User.find_by(username: params[:username])

Just use friendly_id:
#Gemfile
gem 'friendly_id', '~> 5.1'
$ rails generate friendly_id #-> generates initializer
$ rails generate scaffold user name:string slug:string:uniq #-> adds slug column
$ rake db:migrate
#app/models/user.rb
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :username, use: [:slugged, :finders]
end
This will allow you to use the slug / username in lieu of the primary key:
<%= link_to current_user.username, user_path(current_user) #-> <a href="/users/john_jones" %>
You would not have to change your controller code etc for this to work.
--
Your routes can be simplified:
#config/routes.rb
resource :user, path: "", only: :show #-> url.com/:id to users#show
devise_for :users, controllers: { registrations: 'registrations' }, path_names: { sign_in: "login", password: "forgot", confirmation: "confirm", unlock: "unblock", sign_up: "", registration: "signup", sign_out: "logout" }
Whilst I don't know if you can use current_user inside your routes (I'm sure you can but I've not tested), you may wish to use /profile like this:
resource :profile, controller: :users, only: :show
This will send url.com/profile to the users#show action:
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
current_user...
end
end

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 :)

I had a similar problem and made a few changes to routes and it worked here are the sets to do:
under User.rb model
def to_param
username
end
Routes:
resources :users, :path => '/' do
end
Controllers
#user=User.find_by_username(params[:id])
Views
link_to #user.username, #user.username.
Avoid user_path because it would redirect you to www.example.com/users/david
instead follow up this i have noted above
it will www.example.com/david this is better than the first.
hope anyone would be helped.

Related

How to redirect to another page after devise sign in?

First, see my routes :
Rails.application.routes.draw do
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
devise_for :users, controllers: {
registrations: "registrations",
sessions: "sessions"
}
devise_scope :user do
authenticated :user do
root 'appointments#index', as: :authenticated_root
end
unauthenticated do
root 'sessions#new', as: :unauthenticated_root
end
match '/logout', :to => 'devise/sessions#destroy', via: :all
end
resources :appointments do
get :available_slots, on: :collection
resources :notes
resources :images, only: [:show]
end
#patch 'appointments/:id' => "appointments#update_status", as: :update_status
match 'appointments/:id/update_status' => "appointments#update_status", :via => :post
match 'appointments/:id/visited_patient_appointment' => "appointments#visited_patient_appointment", :via => :post
get 'archive' => "appointments#archive"
end
Now, how to redirect to appointments_path after user sign in? There is one devise method called after_sign_in_path_for(resource) which I override in Appointments Controller but still it is not working.
You trying to override in Appointments Controller which is wrong, it will be sessions_controller.rb or application_controller.rb
Try the following in the sessions_controller.rb or application_controller.rb
protected
def after_sign_in_path_for(resource)
stored_location_for(resource) || appointments_path
end
If not have stored_location then he will redirect to appointments_path
If you need to redirect all time to the same page like appointments_path then
protected
def after_sign_in_path_for(resource)
appointments_path
end
See the Devise wiki

Update the route to just show resource/new as compared to user/user_id/resource/new

I am using rails 4 along with devise my routes.rb reads :
devise_for :users, :path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'},
controllers: { registrations: "registrations", omniauth_callbacks: 'omniauth_callbacks' } do
get "/login" => "devise/sessions#new"
get "/signup" => "devise/registrations#new"
get "/logout" => "devise/sessions#destroy"
get "/login" => "devise/sessions#new"
end
resources :users, :only => [:show, :index], :path => "bloggers" do
resources :posts, :path => "articles"
end
Now when I create a new post as the currently signed in user (lets say the id is 1). The URL on the Post -> New action reads - > https://localhost:3000/bloggers/1/articles/new but I want to show
https://localhost:3000/articles/new, as the new action on the post should always be associated to the current_user.
I would imagine this being possible, but no clue how to do it.
Also a user has_many posts.
Help, please?
Authentication
Very simple actually:
#config/routes.rb
# If you have overridden "path_names", you don't need other paths for Devise
devise_for :users, :path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'},
controllers: { registrations: "registrations", omniauth_callbacks: 'omniauth_callbacks' }
resources :posts, as: "articles", path: "articles"
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!, except: :index
def index
#Stuff here
end
end
The bottom line here is that whenever you want to use an authenticated area (especially with Devise), you just need to "protect" the controller#actions which you want to limit access to. The beauty is that you can use the authenticate_user! helper method to make these work
Further to that, you will then be able to just call current_user in your controller (not having to set the user, as you're doing now):
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
#post = current_user.posts.new
end
def create
#post = current_user.posts.new post_params
#post.save
end
private
def post_params
params.require(:post).permit(:x, :y, :z)
end
end

Rails: How do I override Devise controller and Devise routes at the same time?

I am using Rails 4.0.2 and Devise 3.2.2 to handle user registration / authentication.
I have googled and search stackoverflow for answers, can't really find something that can answer my question.
The below code is my routes.rb, I have skip all sessions routes and registration routes but for some reason, Devise is not using my custom registrations_controller.rb because if it is, it should redirect to /pages/success (please see below my registrations_controller.rb )
routes.rb
App::Application.routes.draw do
resources :posts
resources :questions
get "users/:id", to: "users#show"
devise_for :users, :controllers => {:registrations => "registrations"}, :skip => [:sessions, :registrations]
as :user do
get 'login' => 'devise/sessions#new', :as => :new_user_session
post 'login' => 'devise/sessions#create', :as => :user_session
delete 'signout' => 'devise/sessions#destroy', :as => :destroy_user_session
end
as :user do
get '/' => 'devise/registrations#new', :as => :new_user_registration
post 'register' => 'devise/registrations#create', :as => :user_registration
end
get "registrations/update"
get "pages/home"
get "pages/privacy"
get "pages/terms"
get "pages/success"
end
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
protected
def after_inactive_sign_up_path_for(resource)
'/pages/success'
end
end
There are several potential issues you may have:
Skip
If you're skipping the registrations functionality, I'd imagine it would prevent Devise from calling your RegistrationsController?
I would personally do this (correct your routes):
#config/routes.rb
root to: "users#index" (where ever your "logged-in" page is)
devise_for :users, path: "", controllers: { sessions: "sessions", registrations: "registrations" }, path_names: { sign_in: 'login', password: 'forgot', confirmation: 'confirm', unlock: 'unblock', sign_up: 'register', sign_out: 'signout'}
This will give you the routes you need, and will route to the "authenticated" index page in your app, thus either showing the login or registration page for Devise
Definition
The other issue you may have is an incorrect definition of your Devise Registrations controller. We use this code in a very recent development app:
#app/controllers/registrations_controller.rb
class RegistrationsController < ::Devise::RegistrationsController
end
Perhaps you could try using the :: before your Devise::RegistrationsController to see if it calls?

Devise custom after_update_path_for not being called(Rails 4)

I am using devise and want to specify different redirect after updating a user based on a conditional statement. I did follow this https://github.com/plataformatec/devise/wiki/How-To:-Customize-the-redirect-after-a-user-edits-their-profile and it is not calling my custom after_update_path_for method.
routes.rb
devise_for :users, :skip => [:registrations], :controllers => { :registrations => :registrations }
as :user do
get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
put 'users/:id' => 'devise/registrations#update', :as => 'user_registration'
end
The reason I have the skip registrations is because I do not wish to have the new and create routes for the user. I am not sure if the issue is with the routes or something else.
Here is the registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
protected
def after_update_path_for(resource)
binding.pry
if current_user.position == "owner" && current_user.sign_in_count == 1
hub_landing_path
end
end
end
Any help is greatly appreciated. This is really stumping me so if anyone has any ideas I would love to try them out.
You need to change
put 'users/:id' => 'devise/registrations#update', :as => 'user_registration'
to use your custom RegistrationsController controller. So it'll be:
put 'users/:id' => 'registrations#update', :as => 'user_registration'
The accepted answer by #NARKOZ does not work for me for Rails 4. I had to override the Devise Passwords controller like this:
# users/passwords_controller.rb
class Users::PasswordsController < Devise::PasswordsController
protected
def after_resetting_password_path_for(resource)
signed_in_root_path(resource)
end
end
There is documentation on this method here: https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in

Rails 3: Devise overriding sign_up controller woes

Referenced the online documents for Devise but my override is still not working. Any one got any suggestions why not? It just goes to the root after sign in. Sign up works though.
Routes:
root :to => 'pages#index'
get "pages/index"
devise_for :users, :path => 'accounts', :controllers => { :registrations => "registrations" }
match 'profile' => 'profiles#show', :as => 'current_profile'
match 'profile/edit' => 'profiles#edit', :as => 'edit_current_profile'
put 'profile' => 'profiles#update'
resources :users do
resources :profiles
end
Registration Controller:
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
edit_current_profile_path
end
def after_sign_in_path_for(resource)
current_profile_path
end
end
def after_sign_in_path_for(resource)
current_profile_path
end
This goes in the application_controller, not the override class.

Resources