Search code examples
ruby-on-railsruby-on-rails-4draper

Rails Draper Gem raising undefined method for Nested Model


I have various associated model in my application. I have setup Draper to decorate associations upon initialization of the parent class.

I have the following classes:

Customer (has_many :accounts)
Account  (belongs_to :customer && has_many :facilities && has_one :contact)
Contact  (belongs_to :account)
Facility (belongs_to :account)

I initiate a decorator as follows:

@customer = Customer.find_by(:token => params[:token]).decorate

In my account_decorator the following is added:

decorates_association :contact
decorates_association :facilities

...and in my Customer Decorator I have:

decorates_association :accounts

The issue I'm experiencing is that an undefined method exception is shown for any method defined in the facility_decorator. The contact_decorator works perfectly fine. I have made sure that my AR mapping is right, so it can't be that.

Any suggestions?


Solution

  • I solved this problem by eager_loading the associations.

    @customer = Customer.eager_load({ :account => [:facilities]}).find_by(:token => params[:token]).decorate
    

    This also improved the overall query time, so I'm happy with the solution!