The new app I’m working on is using EdgeRails, SimplyRestful and all the rest, so I’ve been learning a lot and bumping into situations I don’t immediately know how to handle. One of those is how to access resources using arbitrary keys in the URL.
For example, let’s say you want to show all the items in your application that have been tagged with the word ‘rails’. In the purely Restful world, your URL for that would be mapped like this:
map.resource :tags
which would give a URL like this /tags/:id where :id represents the unique id of the ‘rails’ tag in the database. While that may be correct, it’s not pretty, and it’s not intuitive for users.
You could hack something together so the system still used a numeric id but appended some textual “meta-data”, as John Susser has discussed. But in my opinion, for this example even that is inadequate. What if the user decides to switch the tag in the URL from ‘rails’ to ‘ruby’? They’d also need to swith the unique id in order for things to work.
Fortunately, Jeremy Voorhis has a fix; it’s a plugin called resource_hacks, and it allows us to use any kind of key we want in the route. So now our mapping becomes:
map.resource :tags, :member_path => ‘/tags/:tag_name’
Which would give us the nice /tags/rails URL we wanted.
There’s some debate on Jeremy’s blog about whether this should get into trunk, and it looks like for now it will stay out due to a difference of opinion about whether it’s right. But it’s clearly called for in my case, so I’m going to go ahead with it.
Can anybody think of a better way of solving this problem, perhaps one that would allow both numeric and non-numeric keys in the URL?