我在这方面遇到过类似的问题,但并不是我正在寻找的...... 忘记这样做的智慧,是否可能这样做?...
/object/update/123?o=section # ==> route to SectionController#update
/object/update/456?o=question # ==> route to QuestionController#update
......如果是的话,会怎么做?
答案 0 :(得分:16)
假设您正在使用Rails 3+,您可以使用"高级约束" (在http://guides.rubyonrails.org/routing.html#advanced-constraints了解更多相关信息)。
以下是解决问题的方法:
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
答案 1 :(得分:11)
比@moonmaster9000仅对routes.rb
的答案更简洁:
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" }
答案 2 :(得分:3)
撇开这样做是否明智的问题,“这可能”的答案是“是”:
class QueryControllerApp
def self.call(env)
controller_name = env['QUERY_STRING'].split('=').last
controller = (controller_name.titleize.pluralize + "Controller").constantize
controller.action(:update).call(env)
rescue NameError
raise "#{controller_name} is an invalid parameter"
end
end
MyRailsApp::Application.routes.draw do
put 'posts/update/:id' => QueryControllerApp
end
路由映射器基本上可以接受任何Rack应用程序作为端点。我们的简单应用程序解析查询字符串,构建控制器名称并调用ActionController方法action
(它本身就是一个Rack应用程序)。未显示:如何使用'o=<controller_name>'