LoginSignup
26
22

More than 5 years have passed since last update.

RailsアプリでURLにidじゃなく、任意文字列でアクセス出来るようにしておく

Last updated at Posted at 2013-01-23

ルーティングルールのresourcesやmemberなどでURLに:idを伴うときに、多くの場合PrimaryKeyを使ってしまいがちですが、将来、要望として任意の文字列で代用したい。なんてことが考えられるので、簡単に修正ができるように備えておきます。

URLに:idを含むとき。

Request: http://APP_URL/users/:id

単純なコントローラ処理の例。

users_controller.rb
class UsersController < ApplicationController
  def show
    user = User.find_by_id(params[:id])
    ...
  end
end

将来に備えた例。

users_controller.rb
class UsersController < ApplicationController
  def show
    user = User.key(params[:id]).first
    ...
  end
  ...
end
user.rb
class User < ActiveRecord::Base
  ...
  scope :key, lambda { |key| where(id: key) }
  ...
end

scopeなどで抽象化しておけば、usernameでアクセスしたくなったときなどにscopeを変更するだけで対応できます。

user.rb
  scope :key, lambda { |key| where(username: key) }

応用が効くので、将来変更するかな?ってときには使っておくといいかもしれません。

26
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
22