Alaap Dhall
Alaap Dhall

Reputation: 351

change routes URL from a random :id to :username in rails

I want to change my routes.rb file in a way so that it changes my current urls

 localhost:3000/amitian/1

to localhost:3000/username

I will provide my routes.rb file for reference

  Rails.application.routes.draw do

 devise_for :amitians

 root 'home#index'
 resources :amitians do
 member do
 get :following, :followers
 end
end
 resources :confessions do
member do
    get 'like' , to: 'confessions#upvote'
    get 'dislike' , to: 'confessions#downvote'
    end
    resources :confessioncomments
  end
    resources :relationships, only: [:create, :destroy]

 end

Upvotes: 2

Views: 1439

Answers (2)

eiko
eiko

Reputation: 5345

As Gregg mentioned, you can change the name of the parameter using:

resources :amitians, param: :username

But you're essentially just renaming a variable. Whether you expect an id or a username is determined in the controller action amitians#show:

@amitian = Amitian.find(param[:id]) # Treat :id as id
@amitian = Amitian.find_by_username(param[:id]) # Treat :id as username

Now, if you want to specifically route to /:username rather than /amitians/:username, you'll have to override that resource route:

resources :amitians, except: [:show] do
  member do
    get :following, :followers
  end
end
get '/:username', to: 'amitians#show'

However, I would recommend against that. Having a parameter directly off root will cause lots of confusion for you when users type in the incorrect url and get a user page instead of a 404 error. Or even worse, what if a user chooses the username 'login' or 'register'? Either your register page would be unreachable or else that user's page would be.

I should also point out that rails convenience methods such as resources, Amitian.find, url_for @amitian, link_to @amitian etc. all use the REST standard which uses numerical IDs.

If you want to use a username instead of IDs, you'll have to stop relying on these methods and change your controllers and views, in addition to your routes file.

Upvotes: 3

user922592
user922592

Reputation:

In rails 4 you can do the following in the route

resources :amitians, param: :username

Upvotes: 0

Related Questions