Search code examples
ruby-on-railsruby-on-rails-3decoratordraper

How can I create a decorator for a set of models with use the same table?


I've got a Rails project which has a large set of models all using the same table through Single Table Inheritance. They are all different types of organisations.

Is it possible to use the draper gem to simplify my model without the need to create a decorator for every model which inherits from my organisation model?


Solution

  • You can explicitly decorate an object without the #decorate method.

    app/decorators/organization_decorator.rb:

    class OrganizationDecorator < Draper::Decorator
      delegate_all
    end
    

    app/controllers/organizations_controller.rb:

    class OrganizationsController < ApplicationController
    
      def show
        @organization = OrganizationDecorator.decorate(Organization.find(params[:id]))
      end
    end
    

    You can also try with:

    app/controllers/organizations_controller.rb:

    class OrganizationsController < ApplicationController
    
      decorates_assigned :organization, with: OrganizationDecorator
    
      def show
        @organization = Organization.find(params[:id])
      end
    end