在我的 rails 应用程序中,我有categories
基于location
. 我想通过使用jsonapi-serializer
's 缓存方法在序列化程序级别缓存这些类别cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 3.hours
。这里的问题是,当我第一次调用它来检索类别时City A
,例如然后稍后尝试从中检索类别City B
仍然会显示City A
的数据。我现在要做的是传递city
给序列化程序,然后将其添加到namespace
使用类似的东西namespace: "jsonapi-serializer/categories/#{:city}"
以区分它们,但我还没有找到这样做的方法。
目前我有这段代码可以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
WhileCategory.active_categories
和Category.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