我有这个资源树:
我希望能够尽可能独立地访问它们。我想避免像
/forum/:forum_id/topic/:topic_id/post/:id
这样的冗余路由因为我只能做 /post/:id
.理想的路线如下所示:
/forums => Forums#index # Lists every forum
/forum/new => Forums#new # New forum
/forum/edit => Forums#edit # Edit forum
/forum/:id => Forums#show # Shows forum
/forum/:id/forums Forums#index # Lists nested forums
/forum/:id/topics => Topics#index # Lists topics inside forum
/forum/:id/topic/new => Topics#new # New topic
/topics => Topics#index # Lists every topic
/topic/:id => Topics#show # Shows topic
/topic/:id/posts => Posts#index # Lists posts inside topic
/topic/:id/post/new => Posts#new # New post
/posts => Posts#index # Lists every post
/post/:id => Posts#show # Shows post
模拟这种情况的最佳方法是什么?
这是我尝试过的:
resources :forums
resources :topics
resources :posts
resources :forums do
resources :topics
end
resources :topics do
resources :posts
end
问题是这些设置创建了很多无用的路由,例如:
/forums/:forum_id/topic/:id # Redundant - /topic/:id
/topics/:topic_id/post/:id # Redundant - /post/:id
/topics/new # No current forum
/posts/new # No current topic
有没有办法指定要创建的路由?
在 Controller 中,如何处理映射到同一操作的多个路由?例如,内部
Topics#index
我如何知道我是否应该处理 GET /forum/:id/topics
或 GET /topics
?
最佳答案
只有 index
上才需要嵌套路由父对象找到资源集合的操作。否则,它是关于 SEO 的。大多数用户不会注意到他们的 url 是如何生成的,也不会关心,所以这都是关于搜索引擎的。我知道你要去哪里,但不生成路由需要更多的工作,因为这个例子中的约定是用一行代码列出一个资源。当然,你已经知道这一点,但这只是我对事情的看法。
a) forms_path #if you want to find all forms
b) topics_path #if you want to find all topics #possible use, maybe in a tag listing.
c) posts_path #if you want to find all posts #probably never use
您可能永远不想找到所有主题,尤其是帖子,但这些将是要使用的路线。
d) form_topics_path(form) #find all topics of a given form
e) form_topic_path(form, topic) #only find one topic on a give form
f) topic_path #find a given topic
在最后两个 e 和 f 中,不需要该表单,因为您知道想要哪个主题。如果您担心 SEO 并让您的 url 适合搜索引擎,那么您可能想要使用 e。
g) form_topic_posts_path(form, topic) #I'm already confused
h) form_topic_post_path(form, topic, post) #still to deep
i) topic_posts_path(topic) #most rails people think two levels is deep enough
j) topic_post_path(topic, post) #might be good for seo
这真的是 SEO 的问题,除了需要其父 ID 才能找到相关帖子的嵌套资源(例如传递
form
)之外,还要保持您的 url 友好。找到相关主题,并通过topic
找到相关的帖子。如果您使用
topic_path
, topics_path
post_path
, post_path
您肯定会错过更好的网址,但就让引擎阅读更好的网址而言,它们确实是不必要的。就不生成路线而言,确实没有对此的需求,因为这会使这比仅在最终目标只是内务管理的一行中声明资源更复杂。
关于ruby-on-rails - 嵌套资源 - 如何避免冗余路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834451/