基于 QueryString 设置 Rails 路由 [英] Setting up Rails routes based on QueryString

查看:20
本文介绍了基于 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+,您可以使用高级约束"(在 http://guides.rubyonrails.org/routing.html#advanced-constraints).

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 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆