RailsでscaffoldするとURLの形式はexample.com/posts/:id
になります。
However, there may be times when you do not want to use id for a parameter.
今回はexample.com/posts/:uuid
の様な形式でidの代わりにuuidを設定してみました。
Add a uuid column when creating the table.
$ rails g scaffold post uuid:string body:text
class CreatePosts < ActiveRecord::Migration[6.0]
def change
create_table :posts do |t|
t.string :uuid, null: false
t.text :body
t.timestamps
end
add_index :posts, :uuid
end
end
$ rails db:migrate
config/routes.rb
resources :posts, param: :uuid
#When setting only the detail screen
# get '/posts/:uuid', to: 'posts#show'
Add a process to set the uuid before saving the data.
app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
private
#add to
def set_uuid
if self.has_attribute?(:uuid) && self.uuid.blank?
self.uuid = SecureRandom.hex(10)
end
end
end
app/models/post.rb
class Post < ApplicationRecord
#add to
before_create :set_uuid
end
If you access the screen as it is, an error will occur, so fix the controller.
app/controllers/posts_controller.rb
def set_post
@post = Post.find_by(uuid: params[:uuid])
end
これでexample.com/posts/:uuid
の形式への設定ができました。
Recommended Posts