Written by Sean Behan on Sun Jun 17th 2012

When I have a controller that takes more than one has_many argument, I think about creating a namespace. This way I may still use my forums, pages controllers w/out needing any conditional logic, testing for the presence of :course_id in the params hash.

map.namespace :courses, :path_prefix=>'/courses/:course_id' do |courses|
  courses.resources :forums
  courses.resources :pages

map.resources :courses map.resources :forums map.resources :pages

# some view.html.erb
<%= courses_forums_path(1) %> /courses/1/forums
<%= courses_pages_path(2) %> /courses/2/pages
# w/ use in a form don't forget to pass an array instead of just the resource (will map to forums_controller)
<%=form_for [:courses, Forum.new] do |f| %><%end%>

in the namespaced controller you can extend the parent controller (if you like) to have access to methods coursescontroller defines.

# app/controllers/courses/forums_controller.rb
class Courses::ForumsController < CoursesController
 before_filter :require_course_login #defined in parent ../courses_controller.rb
 def index

to use the generator to create namespaced controller

./script/generate controller 'courses/forums' 

Tagged with..
#controllers #map #namespace #nested resources #rest #routing #Ruby on Rails

Just finishing up brewing up some fresh ground comments...