【问题标题】:Rails routing /forum/[category_id]/[topic_id]Rails 路由 /forum/[category_id]/[topic_id]
【发布时间】:2015-03-13 19:40:04
【问题描述】:

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

不喜欢默认嵌套路由

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 中吗?

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

      【解决方案2】:

      您可以这样做来自定义路线:

      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]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多