Search code examples
ruby-on-railsruby-on-rails-4routesnested-routescustom-routes

rails routes and custom routing for nested resource


For several projects I need something to simplify my routes to remove the controller name for one of the most important routes. In this case editions, so instead of

domain.com/editions/london/venues/the-venue

We use ->

domain.com/london/venues/the-venue

I've been using this formula for my routing:

  # MUST BE LAST
  resources :editions, path: '' do
    get 'set_session', on: :member
    resources :events
    resources :quiz_masters
    resources :venues
  end

And it works fine, but I feel there's something unpleasant about it. I'm wondering if there's a better alternative, one which also has constraints, so I don't have to worry about sticking it always at the bottom of my routes.

I'm also not sure path: '' is a good way to do it? Even though it works.


Solution

  • Using your example, you probably should constrain it. Either using the Edition.all.map(&:slug) array you included or cache it in some way depending on how big the list is. This way it will be limited and wouldn't necessarily need to be at the bottom of the routes file.

    resources :editions, path: '', :constraints => proc { |req| ['london', 'other_cities'].include?(req.params[:edition_id]) } do
      get 'set_session', on: :member
      resources :events
      resources :quiz_masters
      resources :venues
    end