Skip to content

Commit

Permalink
Associations: #decorate queries DB every time
Browse files Browse the repository at this point in the history
`ActiveRecord::Associations::CollectionProxy#decorate` ignores `target`
(be it already loaded or not) and loads the association again every time
it's called.

That's why unsaved records get missing from the decorated collection.

Resolves drapergem#646,
         drapergem#706,
         drapergem#827.
  • Loading branch information
Alexander-Senko committed Sep 4, 2024
1 parent 7093384 commit 00e99b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/draper/decoratable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ module Decoratable
extend ActiveSupport::Concern
include Draper::Decoratable::Equality

autoload :CollectionProxy, 'draper/decoratable/collection_proxy'

included do
prepend Draper::Compatibility::Broadcastable if defined? Turbo::Broadcastable

ActiveRecord::Associations::CollectionProxy.include CollectionProxy if defined? ActiveRecord
end

# Decorates the object using the inferred {#decorator_class}.
Expand Down
15 changes: 15 additions & 0 deletions lib/draper/decoratable/collection_proxy.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module Draper
module Decoratable
module CollectionProxy
# Decorates a collection of objects. Used at the end of a scope chain.
#
# @example
# company.products.popular.decorate
# @param [Hash] options
# see {Decorator.decorate_collection}.
def decorate(options = {})
decorator_class.decorate_collection(load_target, options.reverse_merge(with: nil))
end
end
end
end

0 comments on commit 00e99b6

Please sign in to comment.