Rails 路由 /forum/[category_id]/[topic_id]

Rails routing /forum/[category_id]/[topic_id]

我想为我的论坛创建嵌套路由,其中​​一个主题属于一个类别。

不喜欢默认的嵌套路由

resources :forum_category do
  resources :forum_topic
end

这会给我类似 /forum_category/[forum_category_id]/forum_topic/[forum_topic_id]


我想要的:

我希望创建以下规则(省略 POST、PATCH、PUT 路由)

/forum                                      => forum_topic#index
/forum/new                                  => forum_topic#new
/forum/[forum_category_id]                  => forum_topic#index
/forum/[forum_category_id]/[forum_topic_id] => forum_topic#show

所以 /forum 是我的索引,forum/open-mic 是我的索引,仅限于带有 seo slug open mic 的类别,最后 /forum/open-mic/lets-talk-about-fun 将是我的论坛主题 lets-talk-about-fun 分类在 open-mic.

这个构建到 Rails 有什么解决方案吗?

如果您只是寻找 GET 请求,您可以这样做:

get '/forum', to: "forum_topic#index", as: :forum_topics
get '/forum/new', to: "forum_topics#new", as: :new_forum_topic
get '/forum/:forum_category_id', to: "forum_topics#show", as: :forum_topic_category
get '/forum/:forum_category_id/:forum_topic_id', to: "forum_topic#show_topic", as: :show_forum_topic_category

您可以将最后两个映射到相同的控制器操作并基于参数重定向,但我建议设置两个单独的操作以提高可读性。

您可以像这样自定义路线:

match "<your-url>", to:"<controller>#<action>", as: "<path-name>", via: :<your method-like GET,POST,DELETE> 

例如获取:

match "forum_category/:forum_category_id/forum_topic/:forum_topic_id", to: "forum_topic#show", as: "show_topic", via: :get

和 POST:

match "forum_category/:forum_category_id/forum_topic", to: "forum_topic#update", as: "update_topic", via: :post

在你的控制器中你有这个参数: param[:forum_category_id]param[:forum_topic_id]