Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

Nesting Resources in Rails Routes.Rb with Namespaces


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 w/ #controllers #map #namespace #nested resources #rest #routingruby on rails