Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translations are always loaded when the record is fetched from the cache #817

Open
amitpatelx opened this issue Jan 9, 2024 · 1 comment

Comments

@amitpatelx
Copy link

I am trying to cache some frequently referenced records in cache. When we read it from cache, the ActiveRecord deserialize well but it hits DB to load translations which is unexpected. How can I prevent it from auto loading?

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
    t.string     :code
  end

  create_table :post_translations, force: true do |t|
    t.references :post
    t.string     :title
    t.string     :locale
  end
end

class Post < ActiveRecord::Base
  translates :title
  
  def self.search_by_code(code)
    Rails.cache.fetch("post_#{code}}", expires_in: 5.minutes) do
      Post.find_by(code:)
    end
  end
end

# first call
Post.search_by_code('ABC')
=> Post Load (0.4ms)
=> Post::Translation Load (0.3ms)

# subsequent calls
Post.search_by_code('ABC')
=> Post::Translation Load (0.3ms)
@amitpatelx amitpatelx changed the title Translations are always loaded where the record is fetched from the cache Translations are always loaded when the record is fetched from the cache Jan 9, 2024
@HDLP9
Copy link

HDLP9 commented Feb 29, 2024

@amitpatelx try doing this:

def self.search_by_code(code)
    Rails.cache.fetch("post_#{code}}", expires_in: 5.minutes) do
      Post.includes(:translations).find_by(code:)
    end
 end

When caching a collection remember to do .load for example Post.includes(:translations).all.load (to avoid querying when reading from cache)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants