datamapper/dm-core — Issue #155: Strategic Eager Loading issue (N+1)
Author: pirj
Created: 2011-10-15 13:08:04+00:00
State: open

Assuming a model:

class Manufacturer
include DataMapper::Resource

property :id, Serial

belongs_to :category
...
end

class Category
include DataMapper::Resource

property :id, Serial
property :code, String
end

Let's run a query which should perform one request:

Manufacturer.all.map do |m|
{
:id => m.id,
:category => m.category.nil? ? nil : m.category.code,
}
end

results in multiple fetching of Category:

SELECT "categories"."id", "categories"."code" FROM "categories" INNER JOIN "manufacturer_categories" ON "categories"."id" = "manufacturer_categories"."category_id" INNER JOIN "manufacturers" ON "manufacturer_categories"."manufacturer_id" = "manufacturers"."id" WHERE "manufacturer_categories"."manufacturer_id" = 29481 GROUP BY "categories"."id", "categories"."code" ORDER BY "categories"."id"