Ruby on Rails: controllers map namespace nested resources rest routing
by bseanvt
leave a comment
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'
Namespacing in Rails
With namespace routes in Rails you can easily create a prefix for select resources. For instance, if you have an admin area or an account dashboard you can give logged in users access to methods that are not otherwise available. To use namespaces define them in config/routes.rb. *Note: this is available for the latest release of Rails, at this time it is 2.3.0. I think it’s supported back until Rails 2.0, but haven’t tested it.
In your config/routes.rb file
map.namespace :dashboard do |dashboard|
dashboard.resources :properties, :collection=>{:available => :get}
end
This namespace will create routes such as dashboard/properties, dashboard/properties/1, essentially all the CRUD paths as well as a collection method “available” dashboard/properties/available. These routes can be accessed in your views with methods such as new_dashboard_property_path, available_dashboard_properties_path etc. If your property model has it’s own controller that isn’t namespaced, properties_controller.rb, remember to modify the property form_for method to tell it to use the dashboard namespace. The normal form_for(@property), method takes just your property object. Instead pass the dashboard symbol inside of an array to form_for
<% form_for [:dashboard, @property] do |f| %><% end %>
You can easily see all of the available paths from the command line using rake routes. I use grep to filter the results for conveinence, because on a large application I don’t necessarily need to see all the routes if I’m working just within a single namespace. rake routes | grep dashboard


