8

Rails routes are great for matching RESTful style '/' separated bits of a URL, but can I match query parameters in a map.connect config. I want different controllers/actions to be invoked depending on the presence of a parameter after the '?'.

I was trying something like this...

map.connect "api/my/path?apple=:applecode", :controller => 'apples_controller', :action => 'my_action'
map.connect "api/my/path?banana=:bananacode", :controller => 'bananas_controller', :action => 'my_action'

For routing purposes I don't care about the value of the parameter, as long as it is available to the controller in the params hash

1
  • 1
    This is probably going to be really tricky to do with the built-in routing engine because it only deals with the path portion of the request. Query parameters are parsed by another layer. It might be possible to use Rack to re-write the URL as it comes in to make it routable. Commented May 11, 2010 at 14:23

2 Answers 2

11

The following solution is based on the "Advanced Constraints" section of the "Rails Routing from the Outside In" rails guide (http://guides.rubyonrails.org/routing.html).

In your config/routes.rb file, include a recognizer class have a matches? method, e.g.:

class FruitRecognizer
  def initialize(fruit_type)
    @fruit_type = fruit_type.to_sym
  end

  def matches?(request)
    request.params.has_key?(@fruit_type)
  end
end

Then use objects from the class as routing constraints, as in:

map.connect "api/my/path", :contraints => FruitRecognizer.new(:apple), :controller => 'apples_controller', :action => 'my_action'
Sign up to request clarification or add additional context in comments.

Comments

0

Unless there is a concrete reason why you can't change this, why not just make it restful?

map.connect "api/my/path/bananas/:id, :controller => "bananas_controller", :action => "my_action"

If you have many parameters, why not use a POST or a PUT so that your parameters don't need to be exposed by the url?

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.