Skip to content

Instantly share code, notes, and snippets.

@rceee
Last active December 14, 2015 03:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rceee/5021916 to your computer and use it in GitHub Desktop.
Save rceee/5021916 to your computer and use it in GitHub Desktop.
How I set up my Rails 3 User model to have a pretty URL/ID "slug" without adding a slug field to the database
resources :users
#plus any applicable authentication routing code, e.g., devise_for :users
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
#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
class UsersController < ApplicationController
def show #example action
@user = User.find_by_slug(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment