friendly_idを使用してみたが、エラーばかりで上手くいかなかったので、独自に実装してみることに。
あと、friendly_idを使うと、パフォーマンスが3倍ほど遅くなるケースもあるようですね。
では、実装していきます。
バージョンと仕様
- ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin19]
- Rails 6.1.0
- devise (4.7.3)
- gem 3.0.3
user.rbにto_paramを追加
今回は、gemのdeviseを導入済みの前提で進める。
また、deviseのUserモデルにusernameカラムも追加している状態。
/:id
と/:username
の両方でアクセスできないようにします。
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :lockable, :timeoutable, :trackable
validates :username,
uniqueness: true,
format: { with: /\A[a-zA-Z\d]+\z/ },
length: { minimum: 3, maximum: 25 }
def to_param
return self.username
end
end
自分の表示させたい_controller.rbに追加
今回、僕の場合は、pagesというコントローラーを生成していて、そこのshow.html.erb
にユーザー名でアクセスできるようにしたかったので、下記のようにしました。
class PagesController < ApplicationController
def index
end
def show
# @users = User.find(params[:id]) # 元々使用してた
@user = User.find_by(username: params[:username]) # 追加
end
end
routes.rbに追加
get '/:username' => 'pages#show', as: :pages_show
これで、http://localhost:3000/ユーザー名
でアクセスできるようになりました!
ちなみに、このユーザーのIDのURLでもみてみると、
このように、なっていました。
これで、無事にユーザー名のURLでアクセス可能になりましたね。