Multiple Routes


Could anyone help with this one.

I want to have two routes into my news stories for the show view, one
by ID and the other by the URL of the story which is stored in the db.

I have two routes setup ...

  map.connect 'itcontractormortgagenews/:id', :controller =>
'posts', :action => 'show'
  map.connect 'itcontractormortgagenews/:url', :controller =>
'posts', :action => 'show'

and I have edited my show method in the controller to ...

if params[:id].to_i > 0
      @post = Post.find(params[:id])
      @post = Post.find_by_sql("select * from posts where URL = '" +
params[:url] + "'").first

The mapping by URL works fine but by ID not. I'm sure there is a
better way to do this.



use the requirement attribute in the routes and use friendly_id gem,

this shows how the use requirement in routes , remember to put specific routes on top and more generic routes below

with frienly_id gem you just have to config.gem and add

has_friendly_id :url in your model , the gem will take care of finding the record and will put the given field in the url query string

Perfect, good video link, thanks radhames!