首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何自定义jsonapi序列化程序缓存命名空间- Rails

如何自定义jsonapi序列化程序缓存命名空间- Rails
EN

Stack Overflow用户
提问于 2020-11-17 08:39:40
回答 1查看 271关注 0票数 0

在我的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。

代码语言:javascript
复制
      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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-19 01:22:17

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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64871832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档