2

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
Alaap Dhall
  • 351
  • 1
  • 3
  • 16
  • This question is very similar to: http://stackoverflow.com/questions/24226378/rails-routes-with-name-instead-of-id-url-parameters which suggests to use friendly_id –  Feb 01 '17 at 17:54
  • I don't feel friendly_id gem is something I want – Alaap Dhall Feb 01 '17 at 17:55

2 Answers2

3

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.

eiko
  • 5,110
  • 6
  • 17
  • 35
0

In rails 4 you can do the following in the route

resources :amitians, param: :username