4

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?

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, good answer. I had gotten as far as trying to use constraints, but I didn't know about the query_string. What is contained in this? How can I use this to look for specific things such as opt or other options. My use case requires me to distinguish between different things such as opt, email, etc.
The query_string is part of the request object. It's literally everything after the "?" in the URL. The example I posted is, like I said, is using a very general regex. If you need more logic than a simple regex, I'd probably put this in the controller and not the routes for maintainability reasons.
2

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" %> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.