Admin controllers with Inherited Resources
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
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:
Filed under: Ruby | 1 Comment
Tags: controllers, gems, inherited_resources, rails, tricks, will_paginate