Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID + Slug name in URL in Rails (like in StackOverflow)

I'm trying to achieve URLs like this in Rails:

http://localhost/posts/1234/post-slug-name

with both ID and slug name instead of either

http://localhost/posts/1234

or

http://localhost/posts/post-slug-name

(right now I have just slug name in URL, so this part is over). How can I do this?

UPD

I found an article on this: http://augustl.com/blog/2009/styling_rails_urls/, instead of /id/slug it suggests to use /id-slug which works perfectly for me, so I'll go with this.

like image 419
Vitaly Avatar asked Apr 13 '10 19:04

Vitaly


3 Answers

Rails has some built-in support for SEO friendly URLs.

You can create a url in the form: "id-title" by simply overriding the to_param method in your model.

This is from one of my projects and creates a url with the id, category name and model name:

def to_param
  "#{id}-#{category.name.parameterize}-#{name.parameterize}"
end 

Rails is smart enough to extract this back into the plain id when you access your controller action, so the following just works:

def show
  @model = Model.find(params[:id])
  render :action => "show"
end
like image 179
Toby Hede Avatar answered Oct 22 '22 08:10

Toby Hede


You'll want to add a regular route with Route Globbing in addition to your resource route (assuming of course that's how your posts routes are defined). For example,

map.resources :posts
map.connect '/posts/:id/*slugs', :controller => 'posts', :action => 'show'
like image 38
Corey Avatar answered Oct 22 '22 09:10

Corey


Use friendly_id. It has one nice feature: you can update your url without breaking the old one.

Generating view url isn't working for me. I just added a small method in the model

def to_param
  self.friendly_id
end
like image 7
Yeameen Avatar answered Oct 22 '22 10:10

Yeameen