2008
12.31

This post is a replica of the information here

Controller
def show
@post = Post.permalinked_find(params[:id])
end

Model
class Post < ActiveRecord::Base
before_save :set_permalink

# A find that finds by permalink, and like the regular find(id), raises an error
# if no record was found.
def self.permalinked_find(key)
find_by_permalink(key) || raise(ActiveRecord::ReordNotFound)
end

def to_param
permalink
end

private

def set_permalink
self.permalink = title_in_permalink_format
end

# Replaces anything that’s not a character or a number with a dash.
def title_in_permalink_format
title.downcase.gsub(/[^a-z0-9]+/i, ‘-’)
end
end

Rails uses the to_param definition to determine what the “id” of the object is. When you do post_path(@post), Rails calls to_param on that @post object. It returns the id by default, but you can re-define it to return whatever you want. The ‘permalink’ attribute, in this case.

No Comment.

Add Your Comment