### Custom Preloads with `goldiload` in Goldiloader Source: https://context7.com/salsify/goldiloader/llms.txt Illustrates how to use the `goldiload` method to define custom preload logic for non-association data such as aggregations, external API calls, or complex queries. It shows examples for simple and complex aggregations. ```ruby class Blog < ActiveRecord::Base has_many :posts # Simple aggregation preload def posts_count goldiload do |ids| # ids contains all Blog IDs from the current context Post.where(blog_id: ids).group(:blog_id).count # Returns: { 1 => 5, 2 => 3, 3 => 8 } end end # Complex aggregation with joins def tags_count goldiload do |ids| Tag .joins(:posts) .where(posts: { blog_id: ids }) .group(:blog_id) .count end end end # Usage - single query loads counts for all blogs blogs = Blog.order(:name).to_a # SELECT * FROM blogs ORDER BY name blogs.map(&:posts_count) # SELECT COUNT(*) FROM posts WHERE blog_id IN (1,2,3) GROUP BY blog_id # Returns: [5, 3, 8] - one query for all blogs! blogs.map(&:tags_count) # SELECT COUNT(*) FROM tags INNER JOIN posts ON... WHERE blog_id IN (1,2,3) GROUP BY blog_id ``` -------------------------------- ### Custom Preload with External API in Ruby Source: https://github.com/salsify/goldiloader/blob/master/README.md This example shows a custom preload for fetching translator data from an external API based on a custom key (`main_translator_reference`). The `goldiload` method is configured with a specific key, and the provided block fetches data from `SomeExternalApi` and indexes it by ID. ```ruby class Post < ActiveRecord::Base def main_translator_reference json_payload[:main_translator_reference] end def main_translator goldiload(key: :main_translator_reference) do |references| # `references` will be an array of `Post#main_translator_reference`s SomeExternalApi.fetch_translators( id: references ).index_by(&:id) end end end ``` -------------------------------- ### Define ActiveRecord Models for Goldiloader Source: https://github.com/salsify/goldiloader/blob/master/README.md Basic setup of ActiveRecord models with associations that Goldiloader will automatically optimize. ```ruby class Blog < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :blog end ``` -------------------------------- ### Install Goldiloader Gem Source: https://context7.com/salsify/goldiloader/llms.txt Add the gem to your Rails application's Gemfile to enable automatic eager loading functionality. ```ruby gem 'goldiloader' ``` -------------------------------- ### Custom Preload with Multiple Keys in Ruby Source: https://github.com/salsify/goldiloader/blob/master/README.md This snippet illustrates how to define a custom preload that relies on multiple keys (e.g., `organizer_id` and `room_id`). The `goldiload` method is invoked with an array of keys, and the block receives a two-dimensional array of key pairs. The example shows grouping fetched notes by these combined keys. ```ruby class Meeting < ActiveRecord::Base def organizer_notes goldiload(key: [:organizer_id, :room_id]) do |id_sets| # +id_sets+ will be a two dimensional array with the # organizer_id and room_id for each item, e.g. # [ # [, ], # [, ] # ] notes = logic_for_fetching_organizer_notes notes.group_by do |report| [report.organizer_id, report.room_id] end end end end ``` -------------------------------- ### Workaround for Limited Associations using Lateral Joins Source: https://github.com/salsify/goldiloader/blob/master/README.md Illustrates how to work around limitations with eager loading `has_one` or `has_many` associations that rely on SQL `LIMIT` clauses. This example uses `INNER JOIN LATERAL` to push the ordering and limiting logic into the database, enabling efficient eager loading. ```ruby class Blog < ActiveRecord::Base has_many :posts has_one :most_recent_post, -> { joins(Arel.sql(<<-SQL.squish)) INNER JOIN LATERAL ( SELECT id FROM posts p1 WHERE blog_id = posts.blog_id ORDER BY published_at DESC LIMIT 1 ) p2 on (p2.id = posts.id) SQL }, class_name: 'Post' has_many :recent_posts, -> { joins(Arel.sql(<<-SQL.squish)) INNER JOIN LATERAL ( SELECT id FROM posts p1 WHERE blog_id = posts.blog_id ORDER BY published_at DESC LIMIT 5 ) p2 on (p2.id = posts.id) SQL }, class_name: 'Post' end ``` -------------------------------- ### Custom Preloads with Custom Keys using `goldiload` Source: https://context7.com/salsify/goldiloader/llms.txt Demonstrates using the `key` parameter with `goldiload` to preload data based on attributes other than the primary key, such as GlobalIDs. It also covers preloading with compound keys and using explicit cache names for multiple preloads. ```ruby class Post < ActiveRecord::Base belongs_to :author, class_name: 'User' def author_global_id author&.to_gid&.to_s end # Preload using a custom key (GlobalID in this case) def author_via_global_id goldiload key: :author_global_id do |gids| # gids contains GlobalID strings for all posts in context GlobalID::Locator.locate_many(gids).index_by do |author| author.to_gid.to_s end end end end # Preload with compound keys (array of attributes) class Meeting < ActiveRecord::Base def organizer_notes goldiload(key: [:organizer_id, :room_id]) do |id_sets| # id_sets is a 2D array: [[org_id_1, room_id_1], [org_id_2, room_id_2], ...] notes = fetch_organizer_notes_from_api(id_sets) notes.group_by { |note| [note.organizer_id, note.room_id] } end end end # Using explicit cache names for multiple preloads class Blog < ActiveRecord::Base def recent_posts_count goldiload(:recent_posts_cache) do |ids| Post.where(blog_id: ids) .where('created_at > ?', 7.days.ago) .group(:blog_id) .count end end def total_posts_count goldiload(:total_posts_cache) do |ids| Post.where(blog_id: ids).group(:blog_id).count end end end ``` -------------------------------- ### Implementing Lateral Joins for Limit and Offset Source: https://context7.com/salsify/goldiloader/llms.txt Shows how to use SQL lateral joins to enable auto-eager loading for associations that would otherwise be incompatible due to limit or offset requirements. ```ruby class Blog < ActiveRecord::Base has_many :posts has_one :most_recent_post, -> { joins(Arel.sql(<<-SQL.squish)) INNER JOIN LATERAL ( SELECT id FROM posts p1 WHERE blog_id = posts.blog_id ORDER BY published_at DESC LIMIT 1 ) p2 on (p2.id = posts.id) SQL }, class_name: 'Post' end ``` -------------------------------- ### Eager Loading ActiveStorage Attachments Source: https://context7.com/salsify/goldiloader/llms.txt Demonstrates that Goldiloader automatically handles the eager loading of ActiveStorage attachments and blobs when accessed. ```ruby class User < ActiveRecord::Base has_one_attached :avatar end users = User.all.to_a users.first.avatar_blob # Automatically eager loaded ``` -------------------------------- ### Define Custom Blog Post Count Preload in Ruby Source: https://github.com/salsify/goldiloader/blob/master/README.md This snippet demonstrates how to define a custom preload for counting associated posts for multiple blog records. It uses a block that accepts an array of blog IDs and returns a hash mapping blog IDs to their post counts. The `goldiload` method handles caching and efficient fetching. ```ruby class Blog < ActiveRecord::Base has_many :posts def posts_count goldiload do |ids| # By default, `ids` will be an array of `Blog#id`s Post .where(blog_id: ids) .group(:blog_id) .count end end end ``` -------------------------------- ### Define ActiveRecord Models for Auto-Loading Source: https://context7.com/salsify/goldiloader/llms.txt Configure standard ActiveRecord models to leverage Goldiloader's automatic eager loading capabilities for associations. ```ruby class Blog < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :blog belongs_to :author, class_name: 'User' has_many :tags, through: :post_tags end class User < ActiveRecord::Base has_many :posts, foreign_key: :author_id has_one :address end ``` -------------------------------- ### Using `fully_load` Association Option in Goldiloader Source: https://context7.com/salsify/goldiloader/llms.txt Explains how to use the `fully_load: true` option for associations to ensure that methods like `size`, `exists?`, or `last` trigger a full association load and auto-eager loading, rather than executing separate SQL queries. ```ruby class Blog < ActiveRecord::Base has_many :posts has_many :posts_fully_load, fully_load: true, class_name: 'Post' end blogs = Blog.order(:name).to_a # Without fully_load - size/exists?/last use SQL queries blogs.first.posts.size # SELECT COUNT(*) FROM posts WHERE blog_id = 1 blogs.first.posts.exists? # SELECT 1 FROM posts WHERE blog_id = 1 LIMIT 1 blogs.first.posts.last # SELECT * FROM posts WHERE blog_id = 1 ORDER BY id DESC LIMIT 1 # With fully_load - triggers full association load and auto-eager loading blogs.first.posts_fully_load.size # Loads ALL posts for ALL blogs, then counts in memory blogs.first.posts_fully_load.exists? # Loads ALL posts for ALL blogs, checks in memory blogs.first.posts_fully_load.last # Loads ALL posts for ALL blogs, returns last in memory # After any of the above, all blogs have their posts loaded blogs.each do |blog| blog.association(:posts_fully_load).loaded? # => true end ``` -------------------------------- ### Enable/Disable Eager Loading with Goldiloader Source: https://context7.com/salsify/goldiloader/llms.txt Demonstrates how to enable and disable Goldiloader's automatic eager loading using both block and non-block forms. It also shows how to check the current enabled status. ```ruby Goldiloader.enabled do # Automatic eager loading is enabled within this block blogs = Blog.all.to_a blogs.first.posts.to_a # Auto-eager loads for all blogs end # Or using non-block form Goldiloader.enabled = true blogs = Blog.all.to_a blogs.first.posts.to_a # Auto-eager loads Goldiloader.enabled = false # Disable for specific code blocks when globally enabled Goldiloader.globally_enabled = true Goldiloader.disabled do # Automatic eager loading is disabled within this block blogs = Blog.all.to_a blogs.first.posts.to_a # Only loads posts for first blog end # Check if enabled if Goldiloader.enabled? puts "Goldiloader is active" end ``` -------------------------------- ### Defining Associations with Eager Loading Constraints Source: https://context7.com/salsify/goldiloader/llms.txt Demonstrates which ActiveRecord associations are compatible with Goldiloader's auto-eager loading and which are not due to SQL constraints like limit, offset, or instance-dependent scopes. ```ruby class Blog < ActiveRecord::Base has_many :posts has_many :limited_posts, -> { limit(2) }, class_name: 'Post' has_many :offset_posts, -> { offset(2) }, class_name: 'Post' has_many :instance_dependent_posts, ->(instance) { where(blog_id: instance.id) }, class_name: 'Post' has_one :post_with_order, -> { order(:id) }, class_name: 'Post' has_many :grouped_posts, -> { group(:blog_id) }, class_name: 'Post' has_many :posts_ordered_by_author, -> { joins(:author).order('users.name') }, class_name: 'Post' has_many :unique_authors, -> { distinct }, through: :posts, source: :author end ``` -------------------------------- ### Integrating with Rails Manual Eager Loading Source: https://context7.com/salsify/goldiloader/llms.txt Explains how Goldiloader complements standard Rails eager loading methods like includes, preload, and eager_load to handle nested associations automatically. ```ruby blogs = Blog.includes(:posts).order(:name).to_a blogs.first.posts.first.author # Auto-loads author for all posts Blog.eager_load(:posts).to_a Blog.preload(:posts).to_a Blog.includes(:posts).to_a ``` -------------------------------- ### Force Association Loading with `fully_load` in Rails Source: https://github.com/salsify/goldiloader/blob/master/README.md Demonstrates how to use the `fully_load: true` option within an ActiveRecord association to ensure that the association is fully loaded, triggering eager loading when necessary. This helps prevent N+1 query problems. ```ruby class Blog < ActiveRecord::Base has_many :posts, fully_load: true end ``` -------------------------------- ### Migrate auto_include association option in Ruby Source: https://github.com/salsify/goldiloader/blob/master/README.md This code demonstrates the migration from the old `auto_include: false` syntax for associations to the new query scope method `auto_include(false)`. This change is necessary for compatibility with newer versions of Goldiloader. ```ruby class Blog < ActiveRecord::Base # Old syntax has_many :posts, auto_include: false # New syntax has_many :posts, -> { auto_include(false) } end ``` -------------------------------- ### Configure Global Goldiloader Settings Source: https://context7.com/salsify/goldiloader/llms.txt Control the global state of Goldiloader by enabling or disabling it across the entire application or specific threads. ```ruby Goldiloader.globally_enabled = false ``` -------------------------------- ### Disable Automatic Eager Loading Source: https://github.com/salsify/goldiloader/blob/master/README.md Demonstrates various methods to disable automatic eager loading, including query scopes, association definitions, and global configuration. ```ruby # Disable for a specific query Blog.order(:name).auto_include(false) # Disable for a specific association class Blog < ActiveRecord::Base has_many :posts, -> { auto_include(false) } end # Disable globally Goldiloader.globally_enabled = false ``` -------------------------------- ### Manage Goldiloader Thread-Local State Source: https://github.com/salsify/goldiloader/blob/master/README.md Shows how to selectively enable or disable automatic eager loading for specific code blocks or threads. ```ruby # Enable for a block Goldiloader.enabled do # logic here end # Disable for a block Goldiloader.disabled do # logic here end # Toggle state manually Goldiloader.enabled = true # ... Goldiloader.enabled = false ``` -------------------------------- ### Handle Nested Association Auto-Loading Source: https://context7.com/salsify/goldiloader/llms.txt Demonstrates how Goldiloader automatically traverses and eager loads nested associations across multiple levels of model relationships. ```ruby blogs = Blog.order(:name).to_a blogs.first.posts.to_a blogs.first.posts.first.author.address ``` -------------------------------- ### Disable Auto-Include on Specific Associations Source: https://context7.com/salsify/goldiloader/llms.txt Configure individual associations to opt-out of automatic eager loading by applying the auto_include(false) scope in the model definition. ```ruby class Blog < ActiveRecord::Base has_many :posts_without_auto_include, -> { auto_include(false) }, class_name: 'Post' end ``` -------------------------------- ### Disable Auto-Include via Query Scope Source: https://context7.com/salsify/goldiloader/llms.txt Use the auto_include(false) method on an ActiveRecord scope to prevent Goldiloader from automatically eager loading associations for that specific query. ```ruby blogs = Blog.auto_include(false).order(:name).to_a blogs.first.posts.to_a ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.