Rails 3 Routing Constraint and Regex

試著忘記壹切 提交于 2020-01-11 04:12:16

问题


I'm looking to match the pattern state/city in the path, unless the state variable equals "auth"

match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => {:state => /(?!auth)/ }

For example, mydomain.com/fl/miami is good. mydomain.com/auth/twitter is bad.

I am using omniauth and it requires that you go to /auth/twitter for authentication, however it is nowhere to be found when I type rake routes.


回答1:


Based on mu is too short's comments, here is the answer I've come up with:

match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => OmniauthPassThru.new

lib/omniauth_pass_thru.rb

class OmniauthPassThru
    def initialize
        @passthru = ["/auth/facebook", "/auth/twitter"]
    end

    def matches?(request)
        return false if @passthru.include?(request.fullpath)
        true
    end
end



回答2:


You should be able to define your /auth route before your state/city routes:

Route priority

Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom.

So this order should do the right thing:

match '/auth/twitter' => ...
match '/:state/:city' => ... 

You might want to avoid the problem altogether by putting your state/city routes into their own namespace:

match '/place/:state/:city' => ...

That leaves the top level clear for other future uses.



来源:https://stackoverflow.com/questions/5931439/rails-3-routing-constraint-and-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!