Rails namespace admin on custom subdomain

后端 未结 2 1332
别那么骄傲
别那么骄傲 2021-01-07 00:24

My rails app is set to use subdomains as described in this RailsCast:

http://railscasts.com/episodes/221-subdomains-in-rails-3

Now, I would like to add an ad

2条回答
  •  迷失自我
    2021-01-07 01:11

    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.

提交回复
热议问题