goddamnyouryan
goddamnyouryan

Reputation: 6906

Rails 4 routes namespace / concern with url variables or parameters

I have an app that has some annoyingly specific routes for the calendar section of the app. They look like this:

MyApp::Application.routes.draw do
  ...
  day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
  get 'days/:month/:day/:year', to: 'schedule#day', constraints: day_constraints, as: :schedule_day
  get 'days/:month/:day/:year/print', to: 'schedule#day_print', constraints: day_constraints
  get 'days/:month/:day/:year/route', to: 'routes#index', constraints: day_constraints
  ...
end

As you can see there's a lot of duplication here. They all route to the schedule controller. I was wondering if there is a way to reduce duplication. I was thinking of a namespace or a concern that looks like this:

MyApp::Application.routes.draw do
  ...
  day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
  namespace 'days/:month/:day/:year' constraints: day_contstraints do
    get 'print', to: 'schedule#day_print'
    get 'route', to: 'routes#index'

    root to: 'schedule#day'
  end
  ...
end

But that throws an error:

'day/:month/:day/:year/schedule' is not a supported controller name. This can lead to potential routing problems.

Any recommendations for how to clean this up?

Upvotes: 1

Views: 2024

Answers (1)

jvperrin
jvperrin

Reputation: 3368

Try using scope instead of namespace and get "/" => "schedule#day" instead of root to: 'schedule#day':

day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
scope 'days/:month/:day/:year', constraints: day_constraints do
  get 'print', to: 'schedule#day_print'
  get 'route', to: 'routes#index'
  get '/', to: 'schedule#day'
end

I also had to add a comma between the scope and constraints.

Upvotes: 2

Related Questions