Nathan Manousos
Nathan Manousos

Reputation: 13848

How do I make part of my route optional?

I have this route, which overrides a resource-generated route:

match "make_tiles(/:tile_type,(:finish))" => "tiles#new", :as => :make_tiles

This allows for nice URLs like /make_tiles/two_two,matte

But I'd like the option to use: /make_tiles/two_two also. Currently only /make_tiles/two_two, works.

How can I get rid of the trailing comma requirement?

Upvotes: 1

Views: 250

Answers (1)

Nick Colgan
Nick Colgan

Reputation: 5508

You can't use a comma to separate fields, and I'm not sure why you'd want to. A comma is not a very good field separator for routes. If you really insist on doing it this way, have the options go into one parameter and separate them manually:

match "make_tiles(/:tile_type_and_finish)" => "tiles#new", :as => :make_tiles

Then in your controller

(tile_type,finish) = params[:tile_type_and_finish].split(",") if params[:tile_type_and_finish].present?

The reason your way isn't allowed is that rails defines the parameter separator as a constant in ActionDispatch::Routing:

SEPARATORS = %w( / . ? )

Otherwise

match "make_tiles(/:tile_type(/:finish))" => "tiles#new", :as => :make_tiles

should work fine.

Upvotes: 3

Related Questions