Changing a Routes Key ID, from /threads/ID to /threads/uuid
I have a threads model, that has Thread (id, uuid, title...)
Here is the path:
When the controller redirects: http://localhost:3000/threads/828b9a2ffc
In the logs I then see:
Started GET "/threads/828b9a2ffc" for 127.0.0.1 at Sat Jul 09 17:24:02 -0700 2011
Processing by ThreadsController#show as HTML
Parameters: {"id"=>"828b9a2ffc"}
The issue here is I don't want 828b9a2ffc to be the ID, I want it to interpruted as uuid in the parameters开发者_如何转开发, so I should see:
Parameters: {"uuid"=>"828b9a2ffc"}
How can that be made possible in the routes file?
Thanks
Maybe I'm missing something obvious but what's wrong with using a route like:
match '/threads/:uuid' => 'threads#show', :via => :get
in your routes.rb
?
The simplest way would probably be:
match 'threads/:uuid' => 'threads#show', :as => :thread
That will make the last part of the url available as params[:uuid]
. If you already have
resources :threads
defined then just put it above that in your routes file and it will override the threads#show
path already defined.
In routes.rb you need something like this:
get 'threads/:uuid', :action => "show", :as => "by_uuid"
This will create a thread_by_uuid_path(thread_object)
helper method but if you also have:
resources :threads
... there will still be the standard show
route which uses :id
and will conflict with the new one you define above. You could define each of the routes manually and deleted the resources :threads
line, but I would tend to leave the route alone and change the controller method like this:
def show
@thread = Thread.find_by_uuid(params[:id]) || Thread.find(params[:id])
...
end
... this way the ID can still be used even though you expect the UUID to be passed.
精彩评论