Rails路由/论坛/ [category_id] / [topic_id]

时间:2015-03-13 19:40:05

标签: ruby-on-rails ruby-on-rails-4 routes

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

不喜欢默认的嵌套路线

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有什么解决方案吗?

2 个答案:

答案 0 :(得分:1)

如果你只是在寻找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

您可以将最后两个映射到相同的控制器操作并根据参数重定向,但为了便于阅读,我建议设置两个单独的操作。

答案 1 :(得分:0)

你可以这样做自定义路线:

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

例如GET:

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]