Module: ArLazyPreload::Relation
- Defined in:
- lib/ar_lazy_preload/ext/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
45 46 47 |
# File 'lib/ar_lazy_preload/ext/relation.rb', line 45 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.
33 34 35 36 |
# File 'lib/ar_lazy_preload/ext/relation.rb', line 33 def lazy_preload(*args) check_if_method_has_arguments!(:lazy_preload, args) spawn.lazy_preload!(*args) end |
#lazy_preload!(*args) ⇒ Object
38 39 40 41 42 43 |
# File 'lib/ar_lazy_preload/ext/relation.rb', line 38 def lazy_preload!(*args) args.reject!(&:blank?) 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 |
# File 'lib/ar_lazy_preload/ext/relation.rb', line 10 def load need_context = !loaded? old_load_result = super setup_lazy_preload_context if need_context old_load_result end |