finiteloop
finiteloop

Reputation: 4496

Rails Routing based on Parameters

I am working on a Rails app, and I am looking for a way to route to different actions in the controller based on the existence of parameters in the url.

For example I want website.com/model to route to model#index, however I want website.com/model?opt=dev to route to model#show. Is there some way this can be done?

Upvotes: 4

Views: 2433

Answers (2)

myagi
myagi

Reputation: 71

Not strictly the same, but if you came to this post and were wondering how to do the same via a POST, then you can do it based on the request_paramters.

for your routes.rb ..

module MyConstraintName  
extend self
  def matches?(request)
    request.request_parameters["routeFlag"] == "routeToModelShow"
  end
end

match "pages/:id", :via=>:post, :controller=>"model", :action=>"show",  :constraints => MyConstraintName

and in your form for example..

<%= hidden_field_tag :routeFlag, "routeToModelShow" %> 

Upvotes: 1

smitjel
smitjel

Reputation: 56

Use route constraints to look at the request object and see if it has URL parameters. If you're using restful routes, you want to put this "one-off" before the restful route. Something like this:

get 'users' => 'users#show', constraints: { query_string: /.+/ }
resources :users

So what this is saying is that if you request "/users?opt=dev" then it will match your special case. Otherwise, it falls through to your normal restful route to the index action. Your model#show action will then have to know to pick up the param[:opt] and do whatever with it.

Also, note that the regex is very loose and it's simply checking for ANY param...you'll want to tighten that up to fit whatever you're trying to do.

Upvotes: 4

Related Questions