Wes Foster
Wes Foster

Reputation: 8910

Routes adding :id into an index resource with a concern

routes.rb:

# Allows a route to be queried by date
# eg: /any_route/dated/2016-01-01/2016-01-04
concern :datable do
  member do
    get 'dated/:start_date/(:end_date)', as: 'dated', constraints: {start_date: /\d{4}-\d{2}-\d{2}/, end_date: /\d{4}-\d{2}-\d{2}/}
  end
end

# I want to make the receipts "datable"
resources :receipts, only: :index, concerns: :datable, action: :index

It seems pretty straight forward, however, the route is being generated as this:

# The route I GET
dated_receipt GET /receipts/:id/dated/:start_date(/:end_date)(.:format)  receipts#index {:start_date=>/\d{4}-\d{2}-\d{2}/, :end_date=>/\d{4}-\d{2}-\d{2}/}

Notice the :id in the route? That shouldn't be there because I'm not querying a specific receipt, just the index.

I'm wanting to generate the following route (which is not currently happening):

# The route I WANT
dated_receipt GET /receipts/dated/:start_date(/:end_date)(.:format)  receipts#index {:start_date=>/\d{4}-\d{2}-\d{2}/, :end_date=>/\d{4}-\d{2}-\d{2}/}

Any idea why the :id is being added into the route?

Upvotes: 0

Views: 120

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52377

What you need is action on collection, not member:

collection do
  get 'dated/:start_date/(:end_date)', as: 'dated', constraints: {start_date: /\d{4}-\d{2}-\d{2}/, end_date: /\d{4}-\d{2}-\d{2}/}
end

You can read more about these routing aspects in docs.

Upvotes: 1

Related Questions