How to decorate nested activerecord associations in Rails

Viewed 662

I am working with a gallery_collection that has_many collection_objects and has_many enhanced_objects through those collection_objects

class Collection < ActiveRecord::Base
 has_many :collection_objects, inverse_of: :gallery_collection
 has_many :enhanced_objects, through: :collection_objects

Ultimately in my GalleryCollection view I am exposing individual enhanced_objects and I would like to expose methods that are available via the EnhancedObject decorator. In my particular example I want to be able to call the method object_record_url

If I decorate the gallery_collection, I can also decorate the collection_objects by using the decorates_association in the GalleryCollectionDecorator

class GalleryCollectionDecorator < Draper::Decorator
  include ActionView::Helpers::UrlHelper

  delegate_all
  decorates_association :collection_objects, with: CollectionObjectDecorator

This works well but I then want to be able to access a specific enhanced_object from the collection_objects and for it to also be decorated.

I tried also using decorates_association in CollectionObjectDecorator

class CollectionObjectDecorator < Draper::Decorator
  delegate_all
  decorates_association :enhanced_objects, with: EnhancedObjectDecorator
end

but this does not appear to work when I initiate the decoration cascade from the level of GalleryCollection.

I am testing the outcomes in the console at the moment with the following:

collection = GalleryCollection.find(3)
decorated_col = collection.decorate 

-- returns a GalleryCollectionDecorator

collection_objects = decorated_col.collection_objects 

-- returns a CollectionObjectDecorator

enhanced_object = collection_objects[0].enhanced_object 

-- returns an undecorated enhanced_object

enhanced_object.object_record_url

-- returns a no method error as it doesn't have access to the decorator method

I would like to be able to access the decorator methods of the enhanced_object that I access from the GalleryCollection. Is there are way to do this using a decorates_association, or is there a better, more 'Rails' way to achieve this?

0 Answers
Related