本文介绍了根据QueryString设置Rails路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也看到了类似的问题,但不是我想要的...
暂时忘记这样做的智慧,是 ...

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 3+,则可以使用高级约束(有关更多信息,请参见)。

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

这篇关于根据QueryString设置Rails路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:20