Redirecting from routes when the constraints fail

送分小仙女□ 提交于 2019-12-08 17:28:10

问题


I want to redirect to a different url when the route constraint fails

Route.rb

match '/u' => 'user#signin', :constraints => BlacklistDomain

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

回答1:


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'

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).

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


来源:https://stackoverflow.com/questions/19636051/redirecting-from-routes-when-the-constraints-fail

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