0

I have resourceful routes set up for a blog (model name: Article).

I want to customize my resourceful route to point to

articles/show/title-of-my-article

Now I read through this:

http://edgeguides.rubyonrails.org/routing.html#customizing-resourceful-routes

But it didn't seem to explain how to overwrite the params not just the :controller or :action. The thing is I could do a singular resource or match a GET request but I'd like to overwrite my resourceful routes so I can still use all the resource helpers (i.e. article_path(@article.title) ) etc.

Can Anyone help me out here, any and all help is much appreciated!

Ben
  • 553
  • 1
  • 13
  • 25

2 Answers2

1

You should override the to_param method on your model:

class Article
  def to_param
    self.title
  end
end

If you want to get a little bit trickier you should read up on generating custom slugs.

Community
  • 1
  • 1
jonnii
  • 28,019
  • 8
  • 80
  • 108
0

In addition to jonni's answer.

Overwriting the to_param method will produce the title when you call the resource helpers like article_path(@article) and it will be passed as the params[:id] to the controller.

Thereafter you will need to find the article more or less manually, i.e. instead of doing

Article.find(params[:id])

You will need to do

Article.find_by_title(params[:id])

I don't remember if that one creates a NotFound exception if the record is not found as the find method do so in that case you will have to check manually if a record was found and raise the exception yourself if it were not in order to trigger the 404-page.

One problem with doing this is that the title might consist of characters that is not allowed or recommended in a URL, so a better approach would be to store a slug based on the title in the database and find it by that.

(You can create the slug automatically by having a filter in the Model and create it by title.parameterize)

Easiest would of course be to use one of the many gems and plugins that already takes care of these things.

Jimmy Stenke
  • 11,140
  • 2
  • 25
  • 20
  • Yes I know I have to strip out all the bad parts of a title to make it URL friendly. I will either write my own or use a gem to manipulate the title in a before_save filter, and save that manipulated string in a URL field in the DB. Then just do overwrite to the to_param method that jonnii provided. Thank you both so much! – Ben Mar 07 '11 at 18:14