[Ruby] Set Rails /users/:id/ to /{ random_srting }: Dedefault Routing

1 minute read

Thing you want to do

  • I want to shorten the path to the #Show action as much as possible
  • I felt that there are many disadvantages in including id in path
  • I want to stop using :id for /users/:id/

I will leave it as a memorandum

make :id of /users/:id/ an attribute other than id

model: using to_param

Generate a URL-safe random string with SecureRandom.urlsafe in url_token, Example of using instead of id

Encoding the current date and time + random numbers may reduce the possibility of collision.

class Article <ApplicationRecord
  attribute :url_token, :string, default: -> {SecureRandom.urlsafe_base64(8)}
.
.
.
  def to_param
    url_token
  end
end

If uuid is as follows (I will use uuid below and leave a description, I think it does not fit the purpose of shortening the URL)

class Article <ApplicationRecord
  attribute :uuid, :string, default: -> {SecureRandom.uuid}
.
.
.
  def to_param
    uuid
  end
end

Controller

After that, rewrite the part that uses params[:id] in the controller to params[:uuid]

Routing: param: :uuid

Rails.application.routes.draw do
  resources :users, param: :uuid
.
.
.
end

Just add param: :uuid This replaces /users/:id with /users/:uuid

I want to change /users/:uuid to /:uuid

Routing: param: :uuid

add path:'/'

Rails.application.routes.draw do
  resources :users, param: :uuid, path:'/'
.
.
.
end

If you check the routing at this time with Rails routes,

       users GET / users#index
             POST / users#create
    new_user GET /new(.:format) users#new
   edit_user GET /:uuid/edit(.:format) users#edit
        user GET /:uuid(.:format) users#show
             PATCH /:uuid(.:format) users#update
             PUT /:uuid(.:format) users#update
             DELETE /:uuid(.:format) users#destroy

users_path overlaps root_path with GET’/’, POST / also fails with Routing Error: No route matches [POST] "/users"

Therefore, as a provisional support, we decided to use only route-based paths for actions other than index, new, and create.

The actual routes.rb is

Rails.application.routes.draw do
  resources :users, only: [:index, :new, :create]
  resources :users, param: :uuid, path:'/', only: [:show, :edit, :update, :destroy]
  .
  .
  .
end

Somehow only Bushik I will try it for the time being

Reference

How to use /:username routing instead of /users/:id on rails Yuichi Takada https://blog.takady.net/blog/2015/11/29/rails-routing-with-username-instead-of- id/