SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

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.


#config/routes.rb
map.namespace :courses, :path_prefix=>'/courses/:course_id' do |courses|
  courses.resources :forums
  courses.resources :pages
end

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
  end
end

to use the generator to create namespaced controller

./script/generate controller 'courses/forums' 

Tagged w/ #controllers #map #namespace #nested resources #rest #routingruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app