Admin controllers with Inherited Resources

27Sep10

fruits
In this post I’ll show how I’ve dried up the admin controllers of a project at Todobebe using inherited_resources, a gem that makes your controllers inherit all restful actions.

Basically I’ve coded two classes to be inherited by the controllers.

The first one is the base for all admin controllers:

#app/controllers/admin/base_controller.rb
class Admin::BaseController < ApplicationController
  before_filter :authenticate_user! #devise filter
  layout "admin"
end

It can be used to set up the behavior of all admin controllers as authentication. For instance the dashboard controller:

#app/controllers/admin/dashboard_controller.rb
class Admin::DashboardController < Admin::BaseController
  def index; end
end

The next class inherits from Admin::BaseController and it uses the method inherit_resources to include the features of Inherited Resources and overrides the method collection to support pagination (will_paginate).

#app/controllers/admin/resources_controller.rb
class Admin::ResourcesController < Admin::BaseController
  inherit_resources
  protected
  def collection
    get_collection_ivar || set_collection_ivar(end_of_association_chain.paginate(:page => params[:page], :per_page => per_page))
  end

  def per_page
    20
  end
end

As a result of that, the controllers for resources has became very simple:

#app/controllers/admin/pictures_controller.rb
class Admin::PicturesController < Admin::ResourcesController
  belongs_to :gallery
end

The above is better than:

#app/controllers/admin/pictures_controller.rb
class Admin::PicturesController < ApplicationController
  layout "admin"
  before_filter :authenticate_user!
  before_filter :load_gallery
  def index
    @pictures = @gallery.pictures.paginate(:page => params[:page], :per_page => 20)
    #(...)
  end
  #(...) new, edit, update, create and destroy...
  private
  def load_gallery
    @gallery = Gallery.find(params[:gallery_id])
  end
end

Right?

Some controllers would have just 1 line:

#app/controllers/admin/galleries_controller.rb
class Admin::GalleriesController < Admin::ResourcesController; end

That is all.

For more information about inherit_resources:

Thanks to Bruno Miranda for the English text revisions. Photo by mattieb

Advertisement


No Responses Yet to “Admin controllers with Inherited Resources”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.