Last active
December 14, 2015 03:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
resources :users | |
#plus any applicable authentication routing code, e.g., devise_for :users |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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