Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.