开发者

getting a 'name' based URL in RESTful routes instead of an id based url

开发者 https://www.devze.com 2022-12-15 10:09 出处:网络
If I implement RESTful routing for a controller \'galleries\' like as follows: map.resources :galleries

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 ?


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.


Then you have to think of what happens if the gallery name is something not very URL-friendly like 'Autumn/Fall2009#1' where you have a forward slash (will change the routing) and a dash (will not be submitted to the server if left unencoded). So, you will need urlencoding when generating such URLs.

0

精彩评论

暂无评论...
验证码 换一张
取 消