R – getting a ‘name’ based URL in RESTful routes instead of an id based url

restroutingruby-on-rails

If I implement RESTful routing for a controller 'galleries' like as follows:

map.resources :galleries 

By default the show url for this controller would be:

/galleries/:id 

which would respond to any requests to /galleries/1 etc.

What if I had a gallery record in the database with a 'name' attribute with value 'portraits'.
Could I do the same as follows:

/galleries/portraits 

instead of doing

/galleries/1 ?

Best Solution

In your Gallery model, add a #to_param method that returns what you want in the URL (in this case, name). In your controller, you still access the value through params[:id] and you'll probably have to use Gallery#find_by_name instead of Gallery#find.

As long as you use the provided helpers (gallery_path, etc.), your URLs should be pretty.