The Rails Way - Namespaces

后端 未结 4 1812
一生所求
一生所求 2020-12-04 08:16

I have a question about how to do something \"The Rails Way\". With an application that has a public facing side and an admin interface what is the general consensus in the

4条回答
  •  忘掉有多难
    2020-12-04 08:31

    There's no real "Rails way" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions.

    That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this:

    routes.rb:

    map.namespace :admin do |admin|
      admin.resources :users
      admin.resources :posts
    end
    

    admin/users_controller.rb:

    class Admin::UsersController < ApplicationController
      before_filter :admin_required
      # ...
    end
    

    application.rb

    class ApplicationController < ActionController::Base
      # ...
    
      protected
      def admin_required
        authenticate_or_request_with_http_basic do |user_name, password|
          user_name == 'admin' && password == 's3cr3t'
        end if RAILS_ENV == 'production' || params[:admin_http]
      end
    end
    

    The conditional on authenticate_or_request_with_http_basic triggers the HTTP Basic auth in production mode or when you append ?admin_http=true to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site.

提交回复
热议问题