Rails routing/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蛞蝓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
您可以映射最后两个相同的控制器操作和重定向基于PARAMS,但我建议设置两个单独的行动为了可读性。
答
你可以自定义路由这样做:
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
你有这样的PARAMS : param[:forum_category_id]
和param[:forum_topic_id]