Resources Controller for RoR Applications

Rails has one basic and most important principle to keep its code DRY (Don’t Repeat Yourself) which means writing same code again and again is a bad thing. But in every rails application, we can often see similar CRUD actions in every controller which violates the DRY principle of Rails. To avoid such kind of duplicacy, we can club the standard CRUD actions at one place. Resources Controller is a plugin to facilitate this approach and to keep your controllers DRY. It introduces some abstraction to help you override the default RESTful functionality in a clean and simple manner. How to use:-
  • To use Resources Controller, firstly you need to download it from and keep it in vendor/plugin folder of your Rails application.
  • In every controller of your application which needs to get this nifty functionality, you just add resource_controller_for line in the controller.
     class PostsController < ApplicationController
           resources_controller_for :posts
    now your posts controller will get all standard CRUD actions, views will get instance variable (i.e. @post or @posts).
  • Here are some general methods of Resources Controller which can be used in your controller for convenience and for making your code RESTful.
  • enclosing_resources: returns array of resources which are nested in that controller.
  • resource_class : returns class of controller’s resource.
  • find_resources: returns collection or array of resources (commonly used in index).
  • find_resource : returns the resource using id from params (commonly used in show, edit, update & destroy).
  • new_resource : initializes a resource of controller’s resource class (commonly used in new).
  • save_resource : saves the newly created or updated resource (commonly used in create).
  • resource : returns the controller’s current resource.
If you want to add some extra functionality into your actions, you can write that action in your controller. Now your newly written action will override the standard action defined in Resources Controller. Isn’t it the Rails DRYness at its best !!