Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Rails routes based on QueryString

I've seen similar questions on this, but not quite what I'm looking for... Forgetting for a moment the wisdom of doing this, is it possible to do this?...

/object/update/123?o=section    # ==> route to SectionController#update
/object/update/456?o=question   # ==> route to QuestionController#update

...and if so, how would that be done?

like image 697
Harv Avatar asked Feb 03 '11 15:02

Harv


People also ask

How do Rails routes work?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.

What is the difference between resource and resources in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.


2 Answers

Assuming you're using Rails 3+, you can use an "Advanced Constraint" (read more about them at http://guides.rubyonrails.org/routing.html#advanced-constraints).

Here's how to solve your example:

module SectionConstraint
  extend self

  def matches?(request)
    request.query_parameters["o"] == "section"
  end
end

module QuestionConstraint
  extend self

  def matches?(request)
    request.query_parameters["o"] == "question"
  end
end

Rails.application.routes.draw do
  match "/object/update/:id" => "section#update", :constraints => SectionConstraint
  match "/object/update/:id" => "question#update", :constraints => QuestionConstraint
end
like image 106
moonmaster9000 Avatar answered Sep 30 '22 07:09

moonmaster9000


More concise than @moonmaster9000's answer for routes.rb only:

match "/object/update/:id" => "section#update", 
  :constraints => lambda { |request| request.params[:o] == "section" }
match "/object/update/:id" => "question#update", 
  :constraints => lambda { |request| request.params[:o] == "question" }
like image 33
Christopher Oezbek Avatar answered Sep 30 '22 06:09

Christopher Oezbek