How to enable two kinds of URLs http://ip:port/questions/:id and http://ip:port/questions/:id/:slug simultaneously?

64 Views Asked by At

I used stringex to implement a more friendly url, like in stackoverflow, now I enable my url as follows:

http://localhost:8000/questions/12/i-want-to-display-the-url-like-stackoverflow

Of course, I found SO steps further, when entering

http://stackoverflow.com/questions/30683457

in url address bar, SO will redirect to the corresponding question

http://stackoverflow.com/questions/30683457/why-i-got-the-error-couldnt-find-article-with-id-ni-hao-wo-zhen-de-henhaoma-w,

but in my app, I used find_by_slug!() to get a record, so, when entering http://localhost:8000/questions/12 it will throw a error:

ActiveRecord::RecordNotFound in QuestionsController#show

Couldn't find Question with slug = 12  

How should I do to enable such two kinds of urls at the same time? Whether I can add a route rule for it, if yes, how to do it?

NOTED

Especially, because my Rails app is based on social-stream engine, which includes a plugin inherited-resources, and inherited-resources has a default method find_by_id(), so I override it using find_by_slug()

UPDATED

After reading some manual about Rails Routing, I enabled http://ip:port/questions/:id, such as, when I enter http://localhost:8000/questions/12 it will redirect to http://localhost:8000/questions/12/i-want-to-display-the-url-like-stackoverflow, my resolution as follows with appending one rule in routes.rb

 match 'questions/:id' => redirect { |params, req|
   id = params[:id]
   slug = Question.find_by_id(params[:id].to_i).slug
   '/questions/' + id + '/' + slug
 }

I don't know whether this is a correct method?

0

There are 0 best solutions below