best way to have words in URL

2 views
Skip to first unread message

Mantat

unread,
Jul 4, 2007, 6:52:39 AM7/4/07
to PeepCode
Hi,

currently, all my routes use the popular :controller/:action/:id
patern and I would like to improve my design by using routes that
replace these with more meaningful name, for exemple, instead of
articles/2 I would like to have articles/name_of_article.

What is the best way to do that? Righ now, I am just thinking about
using a before_filter to fetch the url instead of the ID but I wonder
if there is a better way to do that, and what to do if there are
duplicate names...

Craig Webster

unread,
Jul 4, 2007, 7:31:33 AM7/4/07
to peep...@googlegroups.com
On 4 Jul 2007, at 11:52, Mantat wrote:
> currently, all my routes use the popular :controller/:action/:id
> patern and I would like to improve my design by using routes that
> replace these with more meaningful name, for exemple, instead of
> articles/2 I would like to have articles/name_of_article.
>
> What is the best way to do that?

Depending on how you're creating the links, I'd override the to_param
method of the model to do something like this:

def to_param
"#{id}-#{title.gsub(/[^a-zA-Z0-9]+/, '_')}"
end

That way you can still do Model.find(params[:id]) since it'll just
ignore the text, and you get the title (or whatever other attribute
you want) of the model in the URL.

Cheers,
Craig
--
Craig Webster | Lead Developer | skype: craigwebster
Xeriom Networks | t: 0131 208 3800 | w: http://xeriom.net/

-- Virtual machines, dedicated servers and colocation --

Xeriom Networks Limited.
94/1 Spring Gardens, Abbeyhill, Edinburgh, Scotland.
Registered in England and Wales. Company No. 5961686.

All agreements are made under our standard terms and conditions.
These can
be found at http://xeriom.net/terms_and_conditions


Skyblaze

unread,
Jul 4, 2007, 10:15:46 AM7/4/07
to PeepCode
Putting a "permalink" column/field in the database to fill with the
meaningful name of any row to use as the last parameter of the url.
Then you create an appropriate route in routes.rb with this new
parameter.

Robert Evans

unread,
Jul 4, 2007, 2:27:33 PM7/4/07
to peep...@googlegroups.com
I have a plugin that will take care of the permalizing for you, if you wanted to use it.


Robert

Mantat

unread,
Jul 9, 2007, 7:51:10 AM7/9/07
to PeepCode
Thanks all and sorry for my slow reply. Totaly forgot about this until
this morning when I was making the list of all the stuff still left to
do on my app!

I will investigate each solution!

On Jul 4, 2:27 pm, "Robert Evans" <robertrev...@gmail.com> wrote:
> I have a plugin that will take care of the permalizing for you, if you

> wanted to use it.http://svn.robertrevans.com/plugins/Permalize/
>
> Robert

> --
>
> Robert R Evanshttp://robertrevans.comhttp://rubysnips.com- Hide quoted text -
>
> - Show quoted text -

Reply all
Reply to author
Forward
0 new messages