简体   繁体   English

如果子域不存在,如何重定向请求?

[英]How do I redirect request if a subdomain does not exist?

I've setup a current project with subdomains based on this Railscast. 我已经基于这个 Railscast设置了一个包含子域的当前项目。 I have two models, State and City that each have a :subdomain field in their dataset. 我有两个模型, StateCity ,每个模型在其数据集中都有一个:subdomain字段。 If a user enters a subdomain that matches this :subdomain it presents the appropriate content. 如果用户输入与此匹配的子域:subdomain则会显示相应的内容。

How can I redirect a request if the subdomain does not exist in either the State or City model? 如果StateCity模型中不存在子域,如何重定向请求? For example, I would want blue.domain.com to be redirected to the rails_root . 例如,我希望将blue.domain.com重定向到rails_root

Can someone provide a little guidance on how to redirect if the requested domain does not exist? 如果请求的域不存在,有人可以提供有关如何重定向的一些指导吗?

If your controller, you'll want to add a before_filter where you find the city or state, and then redirect away if not found. 如果您的控制器,您将要添加before_filter,您可以在其中找到城市或州,然后如果找不到则重定向。 Something like: 就像是:

before_filter :find_subdomain

def find_subdomain
  @city_or_state = City.find_by_subdomain(request.subdomain) || State.find_by_subdomain(request.subdomain)
  redirect_to root_path(subdomain: false) if @city_or_state.nil?
end

This is just another way to do the same: 这只是另一种方法:

before_filter :find_subdomain

private
def find_subdomain
  @city_or_state = City.find_by_subdomain(request.subdomain) || State.find_by_subdomain(request.subdomain)
  redirect_to request.domain if @city_or_state.nil?
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM