Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created April 16, 2012 19:31
Show Gist options
  • Save codeincontext/2400950 to your computer and use it in GitHub Desktop.
Save codeincontext/2400950 to your computer and use it in GitHub Desktop.
Eager load a certain number of levels of a nested resource
def self.nested_include(nested_attribute, additional_attributes=[], nesting_level=6)
attributes = additional_attributes
nesting_level.times do
attributes = additional_attributes + [{nested_attribute => attributes}]
end
includes(attributes)
end
scope :with_nesting, nested_include(:children_ordered, [:user, :project])
# Equivalent to
scope :with_nesting, includes(:user, :project, children_ordered: [:user, :project, children_ordered: [:user, :project, children_ordered: [:user, :project, children_ordered: [:user, :project, children_ordered: :children_ordered]]]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment