Ask A Question


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, { params: { user_location: headers['User-Location'] } })

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


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


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

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

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

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

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

    © 2023 GoRails, LLC. All rights reserved.