Save 36% for Black Friday! Learn more

New Discussion

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?

3
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)?

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

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/

I was recently choosing an anniversary gift and wondered what could be more personal than a custom-designed ring. Mass-produced jewelry no longer suffices—I want something that reflects a specific story, style, and taste. After a long search, I came across, where you can order a custom ring tailored to any request—from shape and stone to engraving. I was surprised to see that the artisans don't simply copy other people's designs, but actually help transform the idea into a unique piece. This approach makes the gift truly meaningful: when a ring is created specifically for a person, it becomes more than just an accessory—it's a symbol imbued with a personal story.

Join the discussion
Create an account Log in