Routing title in url


#1

I’ve set up my app to display a post by retrieving its title instead of
id, which works fine, except it looks like this
“/post/the+title+of+post%3F” and I want it to be “the_title_of_post?”
with underscores instead of plusses. Can anyone shed light?


#2

On Wed, Jan 04, 2006 at 08:21:19AM +0100, Kyle Jones wrote:

I’ve set up my app to display a post by retrieving its title instead of
id, which works fine, except it looks like this
“/post/the+title+of+post%3F” and I want it to be “the_title_of_post?”
with underscores instead of plusses. Can anyone shed light?

You could define Post#to_param like this:

class Post < ActiveRecord::Base
def to_param
title.gsub(/\s+/, ‘_’)
end
end

Then:

link_to @post.title, :action => ‘show’, :id => @post

or

link_to @post.title, show_post_url(:id => @post)

to_param will be called implicitly.

marcel


#3

That works at least to create the desired URL, but now i still have to
find_by_post with it, and it doesnt like the new underscores. also how
would you retain characters like “?” instead of “%3F” ?


#4

Kyle Jones wrote:

That works at least to create the desired URL, but now i still have to
find_by_post with it, and it doesnt like the new underscores. also how
would you retain characters like “?” instead of “%3F” ?

find_by_title my bad :stuck_out_tongue:


#5

Kyle Jones wrote:

I’ve set up my app to display a post by retrieving its title instead of
id, which works fine, except it looks like this
“/post/the+title+of+post%3F” and I want it to be “the_title_of_post?”
with underscores instead of plusses. Can anyone shed light?

maybe the plugin acts_as_urlnameable from
http://gironda.org/acts_as_urlnameable/
could help you.


#6

or even acts_as_sluggable. http://dev.2750flesk.com/acts_as_sluggable/