Gemfile
# Friendly ID
gem "friendly_id"
マイグレーション
rails g migration add_slug_to_users
db/migrate/20130217075243_add_slug_to_users.rb
class AddSlugToUsers < ActiveRecord::Migration
def change
add_column :users, :slug, :string
add_index :users, :slug, unique: true
end
end
rake db:migrate
app/models/user.rb
attr_accessible :slug
# Friendly ID
extend FriendlyId
friendly_id :nickname, use: :slugged
# バリデーション
validate :slug, uniqueness: { case_sensitive: false }
slug更新
User.find_each(&:save)
app/controllers/users_controller.rb
# coding: utf-8
class UsersController < ApplicationController
def show( id )
# @user = User.where( id: id ).first
@user = User.where( slug: id ).first
end
end
Started GET "/users/shu0115" for 127.0.0.1 at 2013-02-17 17:37:45 +0900
Processing by UsersController#show as HTML
Parameters: {"id"=>"shu0115"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."slug" = 'shu0115' LIMIT 1
- find
User.find( "shu0115" )
# => SELECT "users".* FROM "users" WHERE "users"."slug" = 'shu0115' LIMIT 1
- where
User.where( id: "shu0115" ).first
# => SELECT "users".* FROM "users" WHERE "users"."id" = 0 LIMIT 1
User.where( slug: "shu0115" ).first
# => SELECT "users".* FROM "users" WHERE "users"."slug" = 'shu0115' LIMIT 1
- update
User.where( slug: "shu0115" ).first.update_attributes( nickname: "shu.0115" )
# => SELECT "users".* FROM "users" WHERE "users"."slug" = 'shu0115' LIMIT 1
# => SELECT "users".* FROM "users" WHERE ("slug" = 'shu-0115' OR "slug" LIKE 'shu-0115--%'ESCAPE '\') AND (id <> 1) ORDER BY LENGTH("slug") DESC, "slug" DESC LIMIT 1
# => UPDATE "users" SET "nickname" = 'shu.0115', "slug" = 'shu-0115', "updated_at" = '2013-02-17 08:24:49.192265' WHERE "users"."id" = 1