[RUBY] Set Rails routing other than id

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 column

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

Set up routing

config/routes.rb


resources :posts, param: :uuid

#When setting only the detail screen
# get '/posts/:uuid', to: 'posts#show'

set uuid

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

Fix controller

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

Set Rails routing other than id
Definitions other than 7 basic actions in Rails
Rails / users /: id / to / {random_srting}: Dedefault Routing
About Rails routing
Rails Routing Basics
[rails] Set validation
Rails 6.0 Routing Summary
Catch Rails Routing Error
[Rails] devise-related routing summary
[Rails] Set Twitter OGP
[Note] Rails3 routing confirmation
Understand Rails "shallow" routing
[Rails] Complete routing settings
Use Rails template function (ERB) other than Controller (Action View)
Organize Rails routing using draw
Rails routing controller view relationship
How to write Rails routing
Rails singular resource routing by resource
[Swift] Set the Style of TableViewCell to something other than Custom