在RESTful路由中获取基于“名称”的URL,而不是基于ID的URL [英] getting a 'name' based URL in RESTful routes instead of an id based url

查看:204
本文介绍了在RESTful路由中获取基于“名称”的URL,而不是基于ID的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我为控制器图库实现RESTful路由,如下所示:

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 

请求/ galleries / 1等。

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 

而不是做

/galleries/1 ?


推荐答案

在您的画廊中模型,添加一个 #to_param 方法,该方法返回URL中想要的内容(在这种情况下,为 name )。在您的控制器中,您仍然可以通过 params [:id] 访问该值,并且可能必须使用 Gallery#find_by_name 而不是 Gallery#find

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.

只要您使用提供的助手( gallery_path 等),您的网址应该很漂亮。

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

这篇关于在RESTful路由中获取基于“名称”的URL,而不是基于ID的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆