约束失败时从路由重定向 [英] Redirecting from routes when the constraints fail
问题描述
当路由约束失败时,我想重定向到其他网址
I want to redirect to a different url when the route constraint fails
Route.rb
match '/ u'=>'user#signin',:constraints => BlacklistDomain
match '/u' => 'user#signin', :constraints => BlacklistDomain
blacklist_domain.rb
blacklist_domain.rb
class BlacklistDomain
BANNED_DOMAINS = ['domain1.com', 'domain2.com']
def matches?(request)
if BANNED_DOMAINS.include?(request.host)
## I WANT TO REDIRECT HERE WHEN THE CONDITION FAILS
else
return true
end
end
end
推荐答案
由于Rails路由是按顺序执行的,因此您可以通过以下方式模仿条件登录:
Because Rails routes are executed sequentially, you can mimic conditional login in the following manner:
# config/routes.rb
match '/u' => 'controller#action', :constraints => BlacklistDomain.new
match '/u' => 'user#signin'
第一行检查是否满足约束条件(例如,是否该请求是从列入黑名单的域发出的)。如果满足约束条件,则将请求路由到 controller#action
(当然,将其替换)。
The first line checks whether the conditions of the constraint are met (i.e., if the request is emanating from a blacklisted domain). If the constraint is satisfied, the request is routed to controller#action
(replace accordingly, of course).
如果满足约束失败的条件(即,请求未列入黑名单),则请求将被路由到 user#signing
。
Should the conditions of the constraint fail to be met (i.e., the request is not blacklisted), the request will be routed to user#signing
.
由于在您的路线中有效处理了此条件逻辑,因此可以简化约束代码:
Because this conditional logic is effectively handled in your routes, your constraints code can be simplified:
# blacklist_domain.rb
class BlacklistDomain
BANNED_DOMAINS = ['domain1.com', 'domain2.com']
def matches?(request)
if BANNED_DOMAINS.include?(request.host)
return true
end
end
end
这篇关于约束失败时从路由重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!