yorch
yorch

Reputation: 7318

Rails 3 Nested resource not in the same namespace

I have the following on my routes file:

namespace :forum do
  resources :topics
  resources :posts do
    resources :comments
  end
end

So Topics and Posts Controllers are inside the Forum module (Forum::TopicsController and Forum::PostsController), but the Comments Controller is not (it's just CommentsController) because it's a polymorphic (so shared between some controllers).

The problem is that the application looks for Forum::CommentsController which obviously does not exist, how can I define no module for that resource?

I've tried, but didn't work:

namespace :forum do
  resources :topics
  resources :posts do
    resources :comments, controller => 'comments'
  end
end

Any help would be appreciated, thanks!

Upvotes: 0

Views: 226

Answers (3)

Sam Peacey
Sam Peacey

Reputation: 6034

It's not the cleanest (and I'm not sure if there's a better way of achieving this), but you could use a scope rather than a namespace, and then explicitely set the controlller for resources in the Forum namespace:

scope '/forum' do
  resources :topics, controller => 'forum/topics'
  resources :posts, controller => 'forum/posts' do
    resources :comments
  end 
end

Upvotes: 1

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

You can also set the route for Comments manually

For example

match '/forums/:forum_id/posts/:post_id/comments/:comment_id' => 'comments#show'

So your Comments controller don't have to sit inside other modules

Upvotes: 1

HungryCoder
HungryCoder

Reputation: 7616

Ok, I guess you want to re-use the codes in Comments controller. Is that right? If so, I do not know any direct answer to this question but I guess you may consider something like that.

comments_controller.rb

module forum
  module posts
   class CommentsController < ApplicationController
     include Commentable
   end
  end
end

commentable.rb

module Commentable 

end

Now you can use this commentable module anywhere you want to use. So, you are re-using common codes with two features: 1. you get freedom to change behavior per controller 2. you have to create separate files for each controller.

Upvotes: 1

Related Questions