【发布时间】:2018-04-27 19:54:51
【问题描述】:
我正在尝试在我的 rails 应用程序上缓存模型。 我有一个模型片段。我第一次创建记录时,会创建一个 redis 计数器缓存。
型号
class Snippet < ApplicationRecord
after_save :clear_cache
def clear_cache
$redis.del("snippets")
end
end
控制器
class SnippetsController < ApplicationController
include SnippetsHelper
def index
@snippets = fetch_snippets
end
def destroy
@snippet.destroy
respond_to do |format|
format.html { redirect_to snippets_url, notice: 'Snippet was successfully destroyed.' }
format.json { head :no_content }
end
end
end
查看
<td><%= link_to 'Destroy', snippet_path(snippet["id"]), method: :delete, data: { confirm: 'Are you sure?' } %></td>
所以每次我加载索引页面时,我都会加载缓存而不是数据库查询。 现在虽然我已经删除了 db 中的一条记录,但它仍然出现在索引页面上。我的问题是如何同时删除数据库记录和缓存记录。
redis 助手
module SnippetsHelper
def fetch_snippets
snippets = $redis.get("snippets")
if snippets.nil?
snippets = Snippet.all.to_json
$redis.set("snippets", snippets)
$redis.expire("snippets", 5.hour.to_i)
end
JSON.load snippets
end
end
【问题讨论】:
标签: ruby-on-rails redis