All threads / How to customize jsonapi-serializer caching namespace
Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to customize jsonapi-serializer caching namespace

mohamed31195 asked in Rails

In my rails application I have categories which are classified based on location. I want to cache these categories on serializer level by using jsonapi-serializer's caching method cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 3.hours. The issue here is that when I call it for the first time to retrieve categories in City A for example then later try to retrieve categories from City B it will still show City A's data. What I'm trying to do now is to pass city to serializer then add it to namespace using something like this namespace: "jsonapi-serializer/categories/#{:city}" in order to differentiate between them but I'm not able to find a way to do so yet.

Currently I have this block of code to retrieve categories based on location then serialize and render a json

      category = Category.active_categories(headers['User-Location'])

      unless category.empty?
        generic_category = Category.all_category
        categories = generic_category, category
        render CategorySerializer.new(categories.flatten, { params: { user_location: headers['User-Location'] } })
      end

While Category.active_categories and Category.all_category are caching the queries as below:

active_categories:

def self.active_categories(user_location)
  Rails.cache.fetch("active_categories/#{user_location}", expires_in: 3.hours) do
    Category.where(status: 'active')
            .joins(:sellers).where(sellers: { status: 'active', is_validated: true })
            .joins(sellers: :cities).where(cities: { name_en: user_location })
            .joins(sellers: :products).where(products: { status: 'available' })
            .where.not(products: { quantity: 0 }).with_attached_cover
            .order(featured: :desc).uniq.to_a
  end
end

all_category:

def self.all_category
Rails.cache.fetch('all_category', expires_in: 24.hours) do
  Category.where(name_en: 'All').with_attached_cover.first
  end
end
Join the discussion

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

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

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

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.