--I want to shorten the path to the #Show action as much as possible
--I felt that there are many disadvantages to including id in path
-I want to stop using : id
for / users /: id /
I will leave it as a memorandum
Generate a URL-safe random string with SecureRandom.urlsafe in url_token Example to use 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
For uuid: (Hereafter, I will adopt uuid and leave an explanation, I think that 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 using 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
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_pathis GET'/' and overlaps with root_path,
POST /also becomes
Routing Error: No route matches [POST]" / users "` and does not work
Therefore, as a tentative measure, we decided to use only actions other than index, new, and create as root-based paths.
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
I'll try this for the time being with just ugly
How to use /: username routing instead of / users /: id in rails · Yuichi Takada https://blog.takady.net/blog/2015/11/29/rails-routing-with-username-instead-of- id /
Recommended Posts