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?
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.
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.
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.
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
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With