[英]How to switch between subdomain and namespace dynamically in rails routes
I would like to create a dynamic routes, like this 我想创建一个像这样的动态路由
https://subdomain.mysite.me/admin
https://mysite.me/subdomain/admin
I can set my routes
for subdomain
constraints, or namespace
, but I don't know how to make them both are available. 我可以为
subdomain
约束或namespace
设置我的routes
,但我不知道如何使它们都可用。
I set up my rails app to use custom subdomains following this awesome RailsCast tutorial by Ryan Bates. 我设置了我的rails应用程序,以便在Ryan Bates使用这个令人敬畏的RailsCast教程之后使用自定义子域。 Users can visit company.lvh.me:3000 and view all its relevant information.
用户可以访问company.lvh.me:3000并查看其所有相关信息。 Now, I would like to add an admin subdomain on the front of the custom subdomain (admin.company.lvh.me:3000).
现在,我想在自定义子域的前面添加一个admin子域(admin.company.lvh.me:3000)。
The idea is that I have specific admins for each blog with special controllers/views. 我的想法是,每个博客都有特定的管理员和特殊的控制器/视图。 So if admin is added to the front of the company subdomain, rails will route through the app/controllers/admin/blogs_controller.rb and show the app/views/admin/blogs/show.html.erb.
因此,如果将admin添加到公司子域的前面,则rails将通过app / controllers / admin / blogs_controller.rb进行路由并显示app / views / admin / blogs / show.html.erb。
I've used the admin namespace and set it as a subdomain in some of my past Rails apps, but when I try that here I need the second subdomain to be dynamic: 我已经使用了admin命名空间并将其设置为我过去的一些Rails应用程序中的子域,但是当我在这里尝试时,我需要第二个子域是动态的:
namespace :admin, path: '/', constraints: { subdomain: 'admin.DYNAMIC' } do
match '/', to: 'blogs#show', via: 'get'
end
So if type admin.company in the subdomain constraint, it works like a charm, but how can make it dynamic? 因此,如果在子域约束中键入admin.company,它就像魅力一样,但如何使其动态化? I've had no luck making it dynamic ('admin.' + Subdomain, etc.) in the routes files, which lead me to the thought: can I just use Ryan Bates's Subdomain class?
我没有运气在路线文件中使它变得动态('admin。'+ Subdomain等),这引出了我的想法:我可以只使用Ryan Bates的子域类吗?
namespace :admin, path: '/', constraints: { subdomain: Subdomain } do
match '/', to: 'blogs#show', via: 'get'
end
class Subdomain
def self.matches?(request)
request.subdomain.present? && request.subdomain != "www"
end
end
Relevant Routes
Prefix Verb URI Pattern Controller#action
admin GET / admin/blogs#show
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.