Search code examples
ruby-on-railsrubyruby-on-rails-4eager-loading

How to DRY up associations in includes?


I have a scope method in which i'm using includes to eager load all the necessary associations. But i'm not sure how to DRY up the associations used in the includes?

Here is the scope defined in the model:

scope :with_associates, (lambda do
    includes(user: :contact,
             appointments: [:customer, templates: :page],
             bundles: appointments: [:customer, templates: :page]])
  end)

How to DRY up this scope?


Solution

  • I Never tried to make that DRY. Anyway, I'll try.

    def appointments_for_includes
      Hash[appointments: [:customer, templates: :page]]
    end
    
    def associations_for_includes
      Hash[user: :contact, bundles: appointments_for_includes].merge(appointments_for_includes)
    end