Skip to content

Please provide a way to preload ancestry #440

@fsateler

Description

@fsateler

Suppose I have these models:

class Area < ApplicationRecord
  has_ancestry orphan_strategy: :restrict
  has_many :people

  def full_name
    # there is a name column
    (ancestors.map(&:name) + [name]).join " - "
  end
end

class Person < ApplicationRecord
  belongs_to :area
end

So each person belongs to an area, which are arranged as a tree. Now if I want to print a list with a set of people and the area they belong to, I get N+1 queries:

data = people.preload(:area).map{|p| [p.name, p.area.full_name]}
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.4ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.4ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.4ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.6ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.6ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.5ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.4ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.3ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.3ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (991) ORDER BY COALESCE("areas"."ancestry", '') ASC
  Area Load (0.4ms)  SELECT "areas".* FROM "areas" WHERE "areas"."id" IN (1129) ORDER BY COALESCE("areas"."ancestry", '') ASC

It would be great to have a way to tell rails to preload the ancestors of a set of records.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions