【问题标题】:How to customize jsonapi-serializer caching namespace - Ruby on Rails如何自定义 jsonapi-serializer 缓存命名空间 - Ruby on Rails
【发布时间】:2020-11-17 08:39:40
【问题描述】:

在我的 Rails 应用程序中,我有 categories,它们根据 location 进行分类。我想通过使用jsonapi-serializer 的缓存方法cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 3.hours 在序列化程序级别缓存这些类别。这里的问题是,当我第一次调用它以检索 City A 中的类别时,然后尝试从 City B 检索类别时,它仍然会显示 City A 的数据。我现在要做的是将city 传递给序列化程序,然后使用类似namespace: "jsonapi-serializer/categories/#{:city}" 的东西将其添加到namespace 以区分它们,但我还没有找到这样做的方法.

目前我有这段代码可以根据位置检索categories,然后序列化并呈现一个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

虽然Category.active_categoriesCategory.all_category 正在缓存如下查询:

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

【问题讨论】:

    标签: ruby-on-rails ruby rubygems ruby-on-rails-6 jsonapi-serialize


    【解决方案1】:

    已经找到了解决方案。只需覆盖缓存方法,如下例所示:

    require 'active_support/cache'
    
    class MySerializer
      include JSONAPI::Serializer
    
      cache_options(store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 3.hours)
    
      def self.record_cache_options(options, fieldset, include_list, params)
        return super(options, fieldset, include_list, params) if params[:user_location].blank?
        opts = options.dup
        opts[:namespace] += ':' + params[:user_location]
        opts
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多