Rails namespace admin on custom subdomain

后端 未结 2 1331
别那么骄傲
别那么骄傲 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:10

    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!

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题