ruby-on-railsruby-on-rails-3routesnested-resources

Rails 3 routes with slashes and nested resources


I'm having trouble adding a slashed slug and nested routes.

If I have these routes:

resources :courses do
  resources :registrations
end

I have these URLs:

/courses/7
/courses/7/registrations

If I change to_param in Course.rb, I can get some slugs happening in the routes:

def to_param
  "#{id}-#{slug}"
end

This then gives me:

/courses/7-title-of-course
/courses/7-title-of-course/registrations

All good so far.

The problem I'm having is after looking at this http://www.miguelsanmiguel.com/2011/03/17/slug-that-slash:

How do I get this to work with nested resources:

Course.rb:

def to_param
  "#{id}/#{slug}"
end

Routes.rb

resources :courses, :constraints => { :id => /[0-9]+\/.+/ } do
  resources :registrations
end

URL:

/courses/7/title-of-course
/courses/7/title-of-course/registrations

If I set things up like that the Course route is fine but the registration routes are broken.

Any tips here?


Solution

  • Try adding constraints:

    resources :courses, :constraints => { :id => /.*/ } do
      resources :registrations
    end