public
Last active

How I set up my Rails 3 User model to have a pretty URL/ID "slug" without adding a slug field to the database

  • Download Gist
User_slugs_without_database.rb
Ruby
1
#This is how I set up my Rails 3 User model to have a pretty URL/ID "slug" without adding a slug field to the database
routes.rb
Ruby
1 2
resources :users
#plus any applicable authentication routing code, e.g., devise_for :users
user.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
class User < ActiveRecord::Base
 
def slug
"#{id}-#{name}".parameterize
end
 
def to_param
slug
end
 
def self.find_by_slug(*args)
record = find(*args)
if record and record.respond_to? :slug
return nil unless record.slug == args.first
end
record
end
 
def self.find_by_slug!(*args)
find_by_slug(*args) or raise ActiveRecord::RecordNotFound
end
def firstname
self.name.match(/^([\w]+)/i )[1].titlecase # a handy bonus class method if you're storing the User's full name in a single field and want to grab just their first name. For example, call in the view via @user.firstname
end
 
end
users_controller.rb
Ruby
1 2 3 4 5 6 7
class UsersController < ApplicationController
 
def show #example action
@user = User.find_by_slug(params[:id])
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.