1

New to rails and I have what I think is a basic question.

In an admin view, there will be varying operations done on different data models. I have a layout "admin" which has various tabs the user clicks to load forms to edit various sets of data.

Should the controller for everything that can be edited in this view be in admin_controller (ie, have an edit_product, edit_user...), or is it better to leave the functions in the controller for each model (say users_controller, products_controller, orders_controller) and specify in the controllers to use the admin layout?

I'm working through my first rails project, and it seems either way works, but obviously I want to follow the right convention going forward so any hint, or a link to an article about this topic would be appreciated.

Thanks,

nktokyo
  • 630
  • 1
  • 7
  • 26

2 Answers2

5

The proper Rails way to do this would be to use Namespaces. I'll give an example below:

Inside your controllers folder, you add a new folder called admin, and for each model you want to edit as an admin, add a controller. Here is a basic blog application:

app/
  models/
  views/
  controllers/
    users_controller.rb
    posts_controller.rb
    comments_controller.rb
    admin/
      users_controller.rb
      posts_controller.rb
      comments_controller.rb

Notice the new folder layer within our controller folder. Inside each of these files, you'll change the definition of the class, from:

class UsersController < ApplicationController

to:

class Admin::UsersController < ApplicationController

Now, within your congif/routes.rb file, you can namespace your routes to the admin namespace, like so:

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

Now, you can go to a URL such as: http://localhost:3000/admin/users/1 and you'll have access to whatever you specified in the admin version of your users controller.

You can read more in this StackOverflow question, and read up on the Routes here.

Community
  • 1
  • 1
Mike Trpcic
  • 25,305
  • 8
  • 78
  • 114
  • Thank you very much for taking the time to write this up. It's exactly what I was looking for and should be included in the standard rails guides. – nktokyo Sep 24 '10 at 04:51
2

Good answer from Mike. I would add that you can see the "standard" rails code for this by using a generator:

# in rails 2.3
$ script/generate controller admin/users

# in rails 3.0
$ rails generate controller admin/users

The slash in the controller name defines a namespace. Also see rake routes for the named paths that it creates, e.g. admin_users_path etc.

Andrew Vit
  • 18,961
  • 6
  • 77
  • 84