Ruby on rails Rails使用通配符路由所有子域
我有一个具有以下模式的现有站点:Ruby on rails Rails使用通配符路由所有子域,ruby-on-rails,Ruby On Rails,我有一个具有以下模式的现有站点: CappedIn.com/users/1 我希望我的用户也可以通过 MyUsername.CappedIn.com 我希望能够捕获所有子域,然后在控制器中执行快速查找并呈现用户配置文件。呈现的URL当然是MyUsername.CappedIn.com 这可能吗?如何实现这一目标 请注意,我目前使用的是Rails3.2,但将迁移到Rails5。因此,Rails 5解决方案将是最好的。要从当前URI的子域中查找用户模型实例,您可以执行以下类似操作(简单、粗糙的示例)
CappedIn.com/users/1
我希望我的用户也可以通过
MyUsername.CappedIn.com
我希望能够捕获所有子域,然后在控制器中执行快速查找并呈现用户配置文件。呈现的URL当然是MyUsername.CappedIn.com
这可能吗?如何实现这一目标
请注意,我目前使用的是Rails3.2,但将迁移到Rails5。因此,Rails 5解决方案将是最好的。要从当前URI的子域中查找
用户
模型实例,您可以执行以下类似操作(简单、粗糙的示例):
通过应用程序控制器中的挂钩查找用户
class ApplicationController < ActionController::Base
# ...
before_action :lookup_user_from_subdomain
# ...
def lookup_user_from_subdomain
@subdomain_user = User.where(username: request.subdomain).first
# Do stuff with @subdomain_user, and/or handle User not found,
# check that subdomain != 'www' if you need to, etc.
end
# ...
end
class UserController < ApplicationController
# ...
def subdomain_profile
@profile = @subdomain_user.profile if @subdomain_user.present?
# You may want to check for request.xhr? and handle
# respnding to js/json here, for ajax requests to display
# profile in a sidebar or somewhere else besides a profile
# page.
# Or, just simply render the profile of the subdomain-user here.
end
# ...
end
class ApplicationController
显示用户控制器的配置文件
class ApplicationController < ActionController::Base
# ...
before_action :lookup_user_from_subdomain
# ...
def lookup_user_from_subdomain
@subdomain_user = User.where(username: request.subdomain).first
# Do stuff with @subdomain_user, and/or handle User not found,
# check that subdomain != 'www' if you need to, etc.
end
# ...
end
class UserController < ApplicationController
# ...
def subdomain_profile
@profile = @subdomain_user.profile if @subdomain_user.present?
# You may want to check for request.xhr? and handle
# respnding to js/json here, for ajax requests to display
# profile in a sidebar or somewhere else besides a profile
# page.
# Or, just simply render the profile of the subdomain-user here.
end
# ...
end
class UserController
注意:我在操作之前使用了,这是一种较新的(Rails~5)约定,而不是在过滤器之前使用
您可以查看有关请求
对象的更多信息,以及有关操作控制器
过滤器的更多信息
查看更多信息,尤其是本地开发人员中用于测试子域的域
如果您计划做一些繁重的工作,比如每个子域(用户)的范围可用数据,或者每个用户使用不同的数据库,或者以某种方式为每个用户处理不同的应用程序体验,请查看。它在Rails应用程序中处理多租户,并内置了通过子域加载用户或帐户的支持 多谢各位。我需要做些什么来确保所有子域都访问我的Rails应用程序吗?@slindsey3000很可能有,但可能是在DNS或Web服务器设置中发生的。