Rails namespace admin on custom subdomain

徘徊边缘 提交于 2019-12-01 01:02:38

I was able to solve this, although it feels a little hackish. Understanding that Rails treats constraints either true or false, I set another constraint inside the initial subdomain constraint check. It splits the subdomain in 2 and examines the first subdomain to see if it equals "admin". If true, it routes to the admin/controllers and admin/views (because of module: "admin"), if not, it routes to the less specific routes that are not inside the "admin" module.

At first I didn't have the namespace :admin, and my route helpers were incorrect (the admin routes weren't prefixed with "admin" and the less specific routes weren't being set since they were duplicates). Once I added namespace :admin and the path: "" (this is important, too, because it removes "admin/" from the URI Pattern), it worked!

One last thing, in the admin/controllers, you have to edit the set_blog method, since "admin.company" is being interpreted instead (see admin/blogs_controller.rb).

routes.rb

Blog::Application.routes.draw do
  constraints(Subdomain) do
    namespace :admin, module: "admin", path: "", constraints: lamda { |r| r.subdomain.split('.')[0] == 'admin' } do
      match '/', to: 'blogs#show', via: 'get'
      ...
    end

    match '/', to: 'blogs#show', via: 'get'
    ...
  end
  ...
end

Rake Routes:

Prefix Verb URI Pattern Controller#Action
 admin GET  /   admin/blogs#show
 ...

​ GET / blogs#show ...

admin/blogs_controller.rb

BlogController < ApplicationController
  before_action :set_blog
  ...
  private
    set_blog
      @blog = Blog.find_by_subdomain!(request.subdomain.split('.')[1])
    end
end

Let me know if there's anything cleaner out there, if not, hopefully this helps others with this issue.

There are several important factors here

Firstly, you'll need to see what the constraint params look like with "multi" subdomains. Instead of splitting, Rails may have admin.company as the subdomain

If we take the idea that Rails will split the subdomains into two, which one is being called as the "parent"?

namespace :admin, path: '/', constraints: { subdomain: 'admin' } do
  constraints(Subdomain) do
    resources :blogs, only: :show, path_names: { show: "" }
  end
end

If you give us some more info on the request (params etc), we'll be in a much better position to help!

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