30

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 Rails community on how to do it?

Namespaces, subdomains or forego them altogether?

Carlos
  • 840
  • 1
  • 7
  • 7

4 Answers4

41

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.

Ben Scofield
  • 6,398
  • 2
  • 23
  • 22
  • 2
    I hate this. The routes get awkward names like this: "new_admin_user_path". It's an operation for an admin to create a new user, not to create a new admin user. It should be called "admin_new_user_path". Ugly. It makes me suspect that I am using namespaces for the wrong thing. – hoff2 Apr 20 '13 at 19:55
5

In some smaller applications I don't think you need to separate the admin interface. Just use the regular interface and add admin functionality for logged in users.

In bigger projects, I would go with a namespace. Using a subdomain doesn't feel right to me for some reason.

psst
  • 51
  • 3
0

Thanks to everyone that answered my question. Looks like the consensus is to use namespaces if you want to as there is no DHH sponsored Rails Way approach. :)

Again, thanks all!

Carlos
  • 840
  • 1
  • 7
  • 7
0

Its surely late for a reply, but i really needed an answer to this question: how to easily do admin areas?

Here is what can be used these days: Active Admin, with Ryan Bates's great intro.

Adit Saxena
  • 1,617
  • 15
  • 25