views:

156

answers:

3

I have List objects which are shown like this:

www.mysite.com/lists/123

Where 123 is the id of the list. What I would like to do is add the title of the list the url so it it more informative(for google or whatever). So I would like it to look like:

www.mysite.com/lists/123/title-of-list-number-123

How do you go about adding to a url like this? If you just enter: www.mysite.com/lists/123 w/o the title, should it find the title and then redirect to a new route?

+1  A: 

This article says exactly what you need to do accomplish this.

http://railscasts.com/episodes/63-model-name-in-url

UPDATE

Have a permalink added to your model, and save as follow to it:

def to_param
  "#{permalink}-#{id}"
end

On your controller, instead of getting things by the id, get them by the pemalink:

@product = Product.find_by_permalink(params[:id])

And that's all you need.

The screen cast explains all the steps on how to do it.

Marcos Placona
+1  A: 

You could also take a look at friendly id, if you're in the mood for a gem/plugin.

nowk
+3  A: 

If you want to keep your find-calls as they are (by id), you could do the opposite of what mplacona suggested:

def to_param
  "#{id}-#{title.parameterize}"
end

With this, your find(params[:id]) will work because it'll convert the string to an integer (can only succeed if the number is in the beginning of the string). So this is will actually work:

List.find("123-my-title")

and will be the same as

List.find(123)

Read more about this and other ways to accomplish this here: http://gregmoreno.ca/how-to-create-google-friendly-urls-in-rails/

The parameterize will automatically convert the string to a "pretty" url. Read more here: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367

If you want a bit more functionality, I'll suggest friendly_id aswell.

simonwh