Rails routes matching query parameters

后端 未结 2 615
野趣味
野趣味 2021-01-12 09:21

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 wa

2条回答
  •  迷失自我
    2021-01-12 09:31

    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'
    

提交回复
热议问题