-
Notifications
You must be signed in to change notification settings - Fork 469
Open
Description
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
endSo 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.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels