views:

62

answers:

2

How can i realize seo friendly urls?

Instead

http://mysite.com/articles/show/2

i would like to use the articlename instead the id

i.e.

mysite.com/articles/show/articlename

or somehow combine id and articlename like this

mysite.com/articles/show/articlename-2

i'm a rails newbie so perhaps you could give me short advice where to change something with what code?

+1  A: 

Look in your article controller, probably in app/controllers/articles.rb. You probably have a method named show which looks up an article by id with something like this:

@article = Article.find(params[:id])

If you know the id is going to be the title of the post instead of its id, you can instead look up your article using

@article = Article.find_by_title(params[:id])

This will allow you to use somewhat ugly URLs like /articles/show/This+is+the+title. If you want to make a slightly nicer URL, you could add a column to your article table (called, say, seo_title) to store the title translated to lowercase with underscores, yielding something like this_is_the_title.

meagar
thanks that works good, but when i use this in the View (<%= link_to "Details", :action => "show", :title => article.title %> it gives me an url like this http://localhost:3000/articles/show?title=articlename but it should be articles/show/articlename
and
@and: If you do it this way, the parameter is still called `id` (even though it contains the title and not the id), so you need to pass `:id => article.title` to `link_to`. If you want the parameter to be called title, you need to change the routes.
sepp2k
yes realized this, works good now also for destroy action, the only problem still is the edit action. i get the error Couldn't find Bookmark with ID=Thisismyfirstarticletitle. the edit.html.erb looks like this <% form_for :article, :url => {:action => "update",:id => @article.title} do |f| %>
and
was a problem with the update action. also wanted to use there this version @bookmark = Bookmark.find_by_title(params[:id]) but seemed that only this works here. still not understand why find_by_title not works for the update action when you i.e. just change another field of the record than the title?
and
A: 

@and

Your question is at once both simple and yet difficult. Best you check out this more mature Stack Overflow post to find your answer:

http://stackoverflow.com/questions/723765/how-do-i-make-the-urls-in-ruby-on-rails-seo-friendly-knowing-a-vendor-name/

It has more examples and more options. While find_by_title is an option, it is far from your best option.

Xu Khan