Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails slugs in URL - using Active Record Model Post's Title attribute instead of ID

I've been trying to make my Rails create URLs to show records by using their title instead of their ID in URL such as:

/posts/a-post-about-rockets

Following a tutorial online I did the following:


Because the ID is no longer in the URL, we have to change the code a bit.

class Post < ActiveRecord::Base   before_create :create_slug    def to_param     slug   end    def create_slug     self.slug = self.title.parameterize   end end 

When a post is created, the URL friendly version of the title is stored in the database, in the slug column.

We also have to update the finds to find records using the slug column instead of using the ID.

class ProjectsController < ApplicationController   def show     @project = Project.find_by_slug!(params[:id])   end end 

At this point it seems to work except showing a record, because find_by_slug! doesnt exist yet.

I'm an extreme newb - where should I be defining it?

like image 931
Elliot Avatar asked Aug 09 '09 22:08

Elliot


1 Answers

This isn't necessarily a direct answer to your question, but have you looked at the Stringex plugin (http://github.com/rsl/stringex)? It's a great way to auto-create slugs for your records.

You can just add something like the following to your model:

class Post < ActiveRecord::Base   acts_as_url :title end 

and it will auto-create slugs from your title and save it to the slug column.

It's also really smart about the way it creates slugs. For example, a title of "10% off, today only" gets turned into "10-percent-off-today-only".

Pretty slick!

like image 138
deadwards Avatar answered Sep 21 '22 12:09

deadwards