添加约束以路由以排除某些关键字

时间:2010-10-26 20:32:06

标签: ruby-on-rails ruby-on-rails-3

我正在使用Rails,如果关键字“events”在url中的任何位置,我想在路由中使用contraint来排除该路由。

我正在使用rails3。

这是我现有的路线。

match ':arg', :to => "devices#show", :constraints => {:arg => /???/} 

我需要在约束中放置一些内容,以便在出现“事件”字时它不匹配。

谢谢

3 个答案:

答案 0 :(得分:7)

不是以一种不打算的方式弯曲正则表达式,而是建议采用这种方法:

class RouteConstraint
  def matches?(request)
    not request.params[:arg].include?('incident')
  end
end

Foo::Application.routes.draw do
  match ':arg', :to => "devices#show", :constraints => RouteConstraint.new
  ...

它更冗长,但最终我觉得更优雅。

答案 1 :(得分:5)

(?!.*?incident).*

可能就是你想要的。

这与How to negate specific word in regex?基本相同。去那里寻求更详细的答案。

答案 2 :(得分:2)

为rails 4.2.5添加@Johannes的答案:

config / routes.rb(非常结束)

constraints(RouteConstraint) do
  get "*anythingelse", to: "rewrites#page_rewrite_lookup"
end

配置/初始化/ route_constraint.rb

class RouteConstraint
  def self.matches?(request)
    not ["???", "Other", "Engine", "routes"].any? do |check|
      request.env["REQUEST_PATH"].include?(check)
    end
  end
end
相关问题