可以在 View 之外使用 jbuilder 片段缓存吗?
我尝试通过以下方式使用 jbuilder 进行缓存:
Jbuilder.encode do |json|
json.cache! ['v1', @people], expires_in: 10.minutes do
json.array! @people do |person|
json.id person.id
json.name person.name
end
end
end
Json 输出实际上包含“缓存!”而不是进行缓存。
输出示例:
"{\"版本\":1,\"人员\":{\"缓存!\":[[{\"id\":1,\"姓名\"
最佳答案
是的,这是可能的,但事情没那么简单,因为 cache!
和 array!
都在 JbuilderTemplate 中定义。这需要一个 View 上下文。您可以在 Rails Controller 中使用 JbuilderTemplate
,如下所示:
template = JbuilderTemplate.encode(view_context) do |json|
json.cache! ['v1', @people], expires_in: 10.minutes do
json.array! @people do |person|
json.id person.id
json.name person.name
end
end
end
设置view_context
非常重要。在 Controller 之外,最好使用 Rails.cache.fetch
(事实上,这正是 Jbuilder does )。
关于ruby - 如何在 View 之外使用rails jbuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405515/