skip to Main Content

I would like to create nested routes for my forum, where a topic belongs to a category.

I’m not liking the default nested routes

resources :forum_category do
  resources :forum_topic
end

which would give me something like /forum_category/[forum_category_id]/forum_topic/[forum_topic_id]


What I want:

I’m looking to create the following rules (leaving out POST, PATCH, PUT routes)

/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

So /forum is my index, forum/open-mic is my index limited to category with seo slug open mic and finally /forum/open-mic/lets-talk-about-fun would be my forum topic lets-talk-about-fun which is categorized under open-mic.

Is there any solution for this build into Rails?

2

Answers


  1. If you’re just looking for GET requests you can do this:

    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
    

    You could map the last two to the same controller action and redirect based on params, but I’d recommend setting up two separate actions for readability.

    Login or Signup to reply.
  2. you can do like this for customize routes:

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

    for example to GET:

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

    and for POST:

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

    in your controller you have this params:
    param[:forum_category_id] and param[:forum_topic_id]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search