How Beautiful is Ruby?
Working with Ruby and in particular Rails, it’s easy to take the beauty inherent in the language for granted. I mean look at this code. If you read it aloud to yourself, it reads like an english sentence that any non programmer can understand.
Forum.categories.map do |category| link_to category.name, category end.to_sentence
Forum categories map do category, link to category name, the category, end and convert to a sentence. The code returns a an english sentence as well.
Fish, French Bread, Coffee and Hamburgers with each linked to the correct resource as well!
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'


