Burak Özmen
Burak Özmen

Reputation: 873

Dynamic routing in Rails

I have 3 different model/controllers. I tried to make something like

// routes.rb
get ':type' => ':type#show'

but as expected, it did not work. I want to route to a controller according to the type specified in URL. How to achieve that?

Upvotes: 0

Views: 596

Answers (3)

bkunzi01
bkunzi01

Reputation: 4561

It sounds like you're looking to use rails Optional Segment Keys. Rails 3 introduced this syntax for defining optional parts of the URL pattern. Try something like:

match ':controller(/:show(/:id))', via: 'get'

Put this route last in your routes file since it will act as a catch-all for almost all routes in your app. that don't get matched before hitting this one. You can make it more specific by specifying a certain action the three different controllers may share etc.

Upvotes: 0

Pavan
Pavan

Reputation: 33542

You can use constraints.

#routes.rb
get "/type" => "controller_A#show", 
  :constraints => lambda { |request| request.params[:type] == "A" }

get "/type" => "controller_B#show", 
  :constraints => lambda { |request| request.params[:type] == "B" }

get "/type" => "controller_C#show", 
  :constraints => lambda { |request| request.params[:type] == "C" }

Upvotes: 0

EdvardM
EdvardM

Reputation: 3072

you could create a generic controller and use redirect_to there to read params[:type] and redirect accordingly, but I don't see why you could not just use proper routes in the first place, eg.

get '/some_path/:id', to: 'mycontroller#method'

if they are standard CRUD controllers, you'd want to consider using resource type routing.

Upvotes: 1

Related Questions