Description
ArLazyPreload is a gem that brings association lazy load functionality to your Rails applications. There is a number of built-in methods to solve N+1 problem, but sometimes a list of associations to preload is not obvious–this is when you can get most of this gem.
Lazy loading is super helpful when the list of associations to load is determined dynamically. For instance, in GraphQL this list comes from the API client, and you'll have to inspect the selection set to find out what associations are going to be used.
This gem uses a different approach: it won't load anything until the association is called for a first time. When it happens–it loads all the associated records for all records from the initial relation in a single query.
ArLazyPreload alternatives and similar gems
Based on the "ORM/ODM Extensions" category.
Alternatively, view ArLazyPreload alternatives based on common mentions on social networks and blogs.
-
ActsAsTaggableOn
A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts. -
ActiveRecord Import
A library for bulk insertion of data into your database using ActiveRecord. -
Audited
Audited (formerly acts_as_audited) is an ORM extension that logs all changes to your Rails models. -
Apartment
Database multi-tenancy for Rack (and Rails) applications -
PublicActivity
Easy activity tracking for models - similar to Github's Public Activity -
Awesome Nested Set
An awesome replacement for acts_as_nested_set and better_nested_set. -
Closure Tree
Easily and efficiently make your ActiveRecord models support hierarchies -
Enumerize
Enumerated attributes with I18n and ActiveRecord/Mongoid support -
Ruby JSON Schema Validator
Ruby JSON Schema Validator -
ActiveRecord Reputation System
An Active Record Reputation System for Rails -
Acts As Tennant
Easy multi-tenancy for Rails in a shared database setup. -
dry-validation
Validation library with type-safe schemas and rules -
ActsAsParanoid
ActiveRecord plugin allowing you to hide and restore records without actually deleting them. -
acts_as_follower
A Gem to add Follow functionality for models -
ranked-model
An acts_as_sortable/acts_as_list replacement built for Rails 4, 5 and 6 -
ActiveRecordExtended
Adds additional postgres functionality to an ActiveRecord / Rails application -
Acts As Commentable
The ActiveRecord acts_as_commentable plugin -
Acts As Commentable with Threading
Similar to acts_as_commentable; however, utilizes awesome_nested_set to provide threaded comments -
Rails PG Extras
Rails PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more. -
Unread
Handle unread records and mark them as read with Ruby on Rails -
activerecord-multi-tenant
Rails/ActiveRecord support for distributed multi-tenant databases like Postgres+Citus -
StoreModel
Work with JSON-backed attributes as ActiveRecord-ish models -
ActsAsTree
ActsAsTree -- Extends ActiveRecord to add simple support for organizing items into parent–children relationships. -
mongoid-history
Multi-user non-linear history tracking, auditing, undo, redo for mongoid. -
activerecord_json_validator
🔩 ActiveRecord::JSONValidator makes it easy to validate JSON attributes against a JSON schema. -
ActiveImporter
Define importers that load tabular data from spreadsheets or CSV files into any ActiveRecord-like ORM. -
arel-helpers
Useful tools to help construct database queries with ActiveRecord and Arel. -
Mongoid Tree
A tree structure for Mongoid documents using the materialized path pattern -
ActiveValidators
Collection of ActiveModel/ActiveRecord validators -
PermenantRecords
Rails Plugin - soft-delete your ActiveRecord records. It's like an explicit version of ActsAsParanoid -
data_miner
Download, unpack from a ZIP/TAR/GZ/BZ2 archive, parse, correct, convert units and import Google Spreadsheets, XLS, ODS, XML, CSV, HTML, etc. into your ActiveRecord models. Uses RemoteTable gem internally. -
ActiveRecord::Turntable
ActiveRecord Sharding Plugin -
Espinita
Audit activerecord models like a boss (and works with rails 4!) -
mini_record
ActiveRecord meets DataMapper, with MiniRecord you are be able to write schema inside your models.
Access the most powerful time series database as a service
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of ArLazyPreload or a related project?
README
ArLazyPreload

ArLazyPreload is a gem that brings association lazy load functionality to your Rails applications. There is a number of built-in methods to solve N+1 problem, but sometimes a list of associations to preload is not obvious–this is when you can get most of this gem.
- Simple. The only thing you need to change is to use
#lazy_preload
instead of#includes
,#eager_load
or#preload
- Fast. Take a look at performance benchmark and memory benchmark
- Perfect fit for GraphQL. Define a list of associations to load at the top-level resolver and let the gem do its job
- Auto-preload support. If you don't want to specify the association list–set
ArLazyPreload.config.auto_preload
totrue
Why should I use it?
Lazy loading is super helpful when the list of associations to load is determined dynamically. For instance, in GraphQL this list comes from the API client, and you'll have to inspect the selection set to find out what associations are going to be used.
This gem uses a different approach: it won't load anything until the association is called for a first time. When it happens–it loads all the associated records for all records from the initial relation in a single query.
Usage
Let's try #lazy_preload
in action! The following code will perform a single SQL request (because we've never accessed posts):
users = User.lazy_preload(:posts).limit(10) # => SELECT * FROM users LIMIT 10
users.map(&:first_name)
However, when we try to load posts, there will be one more request for posts:
users.map(&:posts) # => SELECT * FROM posts WHERE user_id in (...)
Auto preloading
If you want the gem to be even lazier–you can configure it to load all the associations lazily without specifying them explicitly. To do that you'll need to change the configuration in the following way:
ArLazyPreload.config.auto_preload = true
After that there is no need to call #lazy_preload
on the association, everything would be loaded lazily.
If you want to turn automatic preload off for a specific record, you can call .skip_preload
before any associations method:
users.first.skip_preload.posts # => SELECT * FROM posts WHERE user_id = ?
Warning : Using the
ArLazyPreload.config.auto_preload
feature makes ArLazyPreload try to preload every association target throughout your app, and in any other gem that makes association target calls. When enabling the setting in an existing app, you may find some edge cases where previous working queries now fail, and you should test most of your app paths to ensure that there are no such issues.
Relation auto preloading
Another alternative for auto preloading is using relation #preload_associations_lazily
method
posts = User.preload_associations_lazily.flat_map(&:posts)
# => SELECT * FROM users LIMIT 10
# => SELECT * FROM posts WHERE user_id in (...)
Gotchas
- Lazy preloading does not work for ActiveRecord < 6 when
.includes
is called earlier:
Post.includes(:user).preload_associations_lazily.each do |p|
p.user.comments.load
end
- When
#size
is called on association (e.g.,User.lazy_preload(:posts).map { |u| u.posts.size }
), lazy preloading won't happen, because#size
method performsSELECT COUNT()
database request instead of loading the association when association haven't been loaded yet (here is the issue, and here is the explanation article aboutsize
,length
andcount
).
Installation
Add this line to your application's Gemfile, and you're all set:
gem "ar_lazy_preload"
License
The gem is available as open source under the terms of the MIT License.
*Note that all licence references and agreements mentioned in the ArLazyPreload README section above
are relevant to that project's source code only.