如何在 Rails 中自定义 RESTful 路由(基础)
我已通读 Rails 文档 路由,Restful 资源,以及 UrlHelper,并且仍然不了解创建复杂/嵌套路由的最佳实践。我现在正在处理的示例是针对事件的,它有_many rsvps。因此,用户查看事件列表,然后单击注册,然后完成注册过程等。我希望网址如下所示:
/events
/events/123 # possible without title, like SO
/events/123/my-event-title # canonical version
/events/my-category/123/my-event-title # also possible like this
/events/123/my-event-title/registration/new
... and all the restful nested resouces.
问题是,如何使用最少的代码来完成此操作?
这就是我目前所拥有的:
map.resources :events do |event|
event.resources :rsvps, :as => "registration"
end
这让我想到:
/events/123/registration
完成其他两条路线的最佳方法是什么?
/events/123/my-event-title # canonical version
/events/my-category/123/my-event-title # also possible like this
其中 my-category
只是事件可能的 10 种可能类型的数组。
我已修改 Event#to_param
以返回 "#{self.id.to_s}-#{self.title.parameterize}"
,但我更愿意/id/title
具有完整的规范性
I have read through the Rails docs for Routing, Restful Resources, and the UrlHelper, and still don't understand best practices for creating complex/nested routes. The example I'm working on now is for events, which has_many rsvps. So a user's looking through a list of events, and clicks register, and goes through a registration process, etc. I want the urls to look like this:
/events
/events/123 # possible without title, like SO
/events/123/my-event-title # canonical version
/events/my-category/123/my-event-title # also possible like this
/events/123/my-event-title/registration/new
... and all the restful nested resouces.
Question is, how do I accomplish this with the minimal amount of code?
Here's what I currently have:
map.resources :events do |event|
event.resources :rsvps, :as => "registration"
end
That gets me this:
/events/123/registration
What's the best way to accomplish the other 2 routes?
/events/123/my-event-title # canonical version
/events/my-category/123/my-event-title # also possible like this
Where my-category
is just an array of 10 possible types the event can be.
I've modified Event#to_param
to return "#{self.id.to_s}-#{self.title.parameterize}"
, but I'd prefer to have /id/title
with the whole canonical-ness
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您描述的 SEO 友好 URL 不符合 Rails 生成 RESTful 路由的方式,因此您需要使用常规路由来设置它们。例如:
不要觉得您必须对应用程序中的所有内容使用自动生成的 RESTful 路由。它并不总是适合您想要做的事情。甚至 Rails 路由指南也这么说:
Because the SEO-friendly URLs you describe do not conform to the way Rails generates RESTful routes, you will need to use regular routes to set these up. For example:
Don't feel that you have to use the automatically generated RESTful routes for absolutely everything in your application. It's not always a good fit for what you're trying to do. Even the Rails routing guide says so:
您是否看过 Rails 路由指南?它提供了大量信息来帮助您了解路由器,并包含有关嵌套资源。
Have you looked at the Rails routing guide? It's got lots of info to get you understanding the router and includes a section on nested resources.