Module: ArLazyPreload::Relation
- Defined in:
- lib/ar_lazy_preload/active_record/relation.rb
Overview
ActiveRecord::Relation patch with lazy preloading support
Instance Attribute Summary collapse
- #lazy_preload_values ⇒ Object readonly
Instance Method Summary collapse
-
#lazy_preload(*args) ⇒ Object
Specify relationships to be loaded lazily when association is loaded for the first time.
- #lazy_preload!(*args) ⇒ Object
-
#load ⇒ Object
Enhanced #load method will check if association has not been loaded yet and add a context for lazy preloading to loaded each record.
Instance Attribute Details
#lazy_preload_values ⇒ Object
49 50 51 |
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 49 def lazy_preload_values @lazy_preload_values ||= [] end |
Instance Method Details
#lazy_preload(*args) ⇒ Object
Specify relationships to be loaded lazily when association is loaded for the first time. For example:
users = User.lazy_preload(:posts)
users.each do |user|
user.first_name
end
will cause only one SQL request to load users, while
users = User.lazy_preload(:posts)
users.each do |user|
user.posts.map(&:id)
end
will make an additional query.
38 39 40 41 |
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 38 def lazy_preload(*args) check_if_method_has_arguments!(:lazy_preload, args) spawn.lazy_preload!(*args) end |
#lazy_preload!(*args) ⇒ Object
43 44 45 46 47 |
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 43 def lazy_preload!(*args) args.flatten! self.lazy_preload_values += args self end |
#load ⇒ Object
Enhanced #load method will check if association has not been loaded yet and add a context for lazy preloading to loaded each record
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 10 def load need_context = !loaded? result = super if need_context Context.register( records: ar_lazy_preload_records, association_tree: lazy_preload_values ) end result end |