I have a web app made with Ruby On Rails. For now when I want to display an object I have to access the following page: http://mywebapp.com/object/1234 with 1234 the id of the object.
I would like to encode that object id and have the following result: http://mywebapp.com/object/5k (it is just an example).
How can it be done?
Many thanks,
Martin
You could probably do this with Base64 encoding (although if you're really trying to keep the internal id secret someone could probably guess you're using Base64 encoding and easily determine the id).
Your controller would need to look a bit like this
Now actually encoding your URLs is going to be a little bit trickier - I'll look into it as it seems like an interesting problem (but I'm not making any promises).
A bit of reading reveals that ActionView uses the to_param method in url_for to get the id of an object. We can override this in the model itself to encode the id like so
Everything I've written here is conjectural. I haven't done this before or tested the code so I can't give any guarantee as to whether it will work or whether it will introduce unforeseen problems. I'd be very interested to hear how you go.
All these converting methods are reversible, so IMHO if your object has some name or title or whatever, then the best way is adding a slug. In such case add a new attribute :slug to your object, let automatically generate it's value from object name (or something else) on the model:
then the URL can be http://mywebapp.com/object/my_object_slug, because in action you find the object via this slug:
Don't forget modify routes.rb: