Ask A Question

Notifications

You’re not receiving notifications from this thread.

When pre/eager loading an association, is there any way to get the associated data from a cache?

Alan Oliveira asked in Rails
class Category < ActiveRecord::Base
  # columns: name
  has_many :books
end

class Book < ActiveRecord::Base
  # columns: title, category_id
  belongs_to :category
end

Given the above example, let's suppose Category rarely changes and categories table is quite small but it can't be an enum.
Is there any way to cache Category.all and use it in all future Book.includes(:category)?

Reply

It seems not to be possible,
The best I could find is described below, but both are terrible.

Create a scope overriding preload_associations to force the preloader get the data from the cache

def preload_associations(records)
  ActiveRecord::Associations::Preloader.new(records: records, associations: :category, available_records: Category.all_from_my_awesome_cache).call
  super
end

Override association to manually load the record before it tries to fetch from db

def association(name)
  super.tap do |assoc|
    next if assoc.loaded? || assoc.reflection.class_name != "Category"
    assoc.target = Category.all_from_my_awesome_cache.find { it.id == assoc.owner.category_id }
    assoc.loaded!
  end
end

After all, the best way is the simplest one, just override category method on Book class

Reply

To efficiently retrieve associated data from a cache during pre/eager loading, implement caching strategies such as memory caching or using tools like Redis. This minimizes database calls and speeds up data access, just like the fast-paced action in the Snow Rider 3D game. Fine-tuning your cache can enhance performance significantly, ensuring swift data delivery to your application. https://snowrider-3d.io/

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 88,096+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.