drapergem / draper

Decorators/View-Models for Rails Applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

model.assocations.decorate loads the association even if it is preloaded (AR)

PragTob opened this issue Β· comments

Hi there,

first and foremost - thanks for draper πŸŽ‰

In our application I run into the problem that I want to explicitly decorate an association not as part of the decorator definition (sadly this easily leads to performance problems) so we want to do model.association.decorate but this seems to reload the objects from the database even if they were preloaded before.

See this snippet:

[13] pry(main)> ts = TourSchedule.includes(:tour_schedule_plans).find(104281); nil
  TourSchedule Load (1.0ms)  SELECT  "tour_schedules".* FROM "tour_schedules" WHERE "tour_schedules"."id" = $1 LIMIT $2  [["id", ID], ["LIMIT", 1]]
  TourSchedulePlan Load (1.3ms)  SELECT "tour_schedule_plans".* FROM "tour_schedule_plans" WHERE "tour_schedule_plans"."tour_schedule_id" = ID
=> nil
[14] pry(main)> ts.tour_schedule_plans.loaded?
=> true
[15] pry(main)> ts.tour_schedule_plans.to_a; nil
=> nil
[16] pry(main)> ts.tour_schedule_plans.decorate.to_a; nil
  TourSchedulePlan Load (0.8ms)  SELECT "tour_schedule_plans".* FROM "tour_schedule_plans" WHERE "tour_schedule_plans"."tour_schedule_id" = $1  [["tour_schedule_id", ID]]
=> nil

Draper version in use is 3,0.0.

Somewhat related issues (associations and preloading) are:

  • #646 (the way we decorate just differs)
  • #812

edit: FYI mapping over all objects and decorating them instead seems to be a fine workaround as indicated by early testing ts.tour_schedule_plans.map &:decorate

Thanks!

@codebycliff I don't think there is any way to avoid this query when .decorate calls .all even if it was preloaded πŸ€”
https://github.com/drapergem/draper/blob/master/lib/draper/decoratable.rb#L58