Rails 路由/控制器 - 列出集合的子集
我有一个博客,其中包含多个类别的帖子。我想为每个类别提供一个单独的登录页面,其中列出了该类别中的所有博客帖子。
为每个登陆页面生成路线和控制器操作的适当方法是什么?在我的帖子控制器中创建多个索引式操作(每个类别一个操作)是否会违反 REST 精神?如果是这样,我还应该怎么做?
例如,我的博客可能有两个类别:“音乐”和“电影”。
GET /posts/ # would list all posts.
GET /music/ # would list all posts in the "Music" category.
GET /movies/ # would list all posts in the "Movies" category.
如果这个问题有一个明显的答案,或者如果我完全问错了问题,我深表歉意。我对 Rails 和 REST 都很陌生,我正在尝试了解构建应用程序的最佳方法。
I have a blog with posts in multiple categories. I'd like to give each category an individual landing page that lists all of the bog posts in that category.
What is the appropriate way to generate the routes and controller actions for each of these landing pages? Would it violate the spirit of REST to create multiple index-esque actions (one action per category) in my posts controller? If so, how else should I do it?
For example, my blog might have two categories, "Music" and "Movies".
GET /posts/ # would list all posts.
GET /music/ # would list all posts in the "Music" category.
GET /movies/ # would list all posts in the "Movies" category.
Apologies if this question has an obvious answer, or if I'm asking the wrong question entirely. I'm new to both Rails and REST and I'm trying to understand the best way to structure applications.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定它是否完全符合 REST 精神(我还没有完全理解它),所以我将把问题的这一部分留给其他人。由于
collection
方法的存在来扩展 RESTful 路由< /a>,我认为只要您不滥用它,这是允许的。不过,我不认为没有“/posts/”前缀的路由是一件好事,因为它会导致“/music/”路径与完全不同的资源相关。
你可以做这样的事情:(
在routes.rb中)
...然后将类似索引的操作添加到你的控制器中,例如:
如果你有一组有限且恒定的类别,可以通过这种方式进行干燥:
I'm not sure it's totally in REST spirit (i do not fully understand it yet), so i'll leave that part of the question to someone else. As the
collection
method exists to extend RESTful routes, i assume that it is permitted as long as you don't abuse of it.I don't think, though, that having routes with no "/posts/" prefix is a good thing, because it would induce that the "/music/" path for instance relates to a completely different resource.
you can do something like this :
(in routes.rb)
... and then add index-like actions to your controller, e.g.:
if you have a limited and constant set of categories, this can be DRYed up this way: