Logidze 使用教程
logidzeDatabase changes log for Rails项目地址:https://gitcode.com/gh_mirrors/lo/logidze
项目介绍
Logidze 是一个用于 Ruby on Rails 应用的日志记录工具,它能够在数据库层面跟踪记录的变更历史。Logidze 通过在数据库表中添加一个 log_data
列来存储变更历史,这个列是一个 JSONB 类型的字段,可以存储每次变更的详细信息,包括变更前后的数据、变更时间、变更者等。
项目快速启动
安装 Logidze
首先,将 Logidze 添加到你的 Gemfile 中:
gem "logidze", "~> 1.1"
然后运行 bundle 安装:
bundle install
初始化 Logidze
生成并运行初始化迁移:
bundle exec rails generate logidze:install
bundle exec rails db:migrate
为模型启用 Logidze
假设你有一个 Post
模型,你需要为它启用 Logidze:
bundle exec rails generate logidze:model Post
bundle exec rails db:migrate
在你的 Post
模型中添加 has_logidze
:
class Post < ApplicationRecord
has_logidze
end
使用 Logidze
现在你可以通过 log_data
访问 Post
的变更历史:
post = Post.create(title: "Hello, Logidze!")
post.update(title: "Hello, World!")
post.log_data # 获取变更历史
应用案例和最佳实践
跟踪责任人
你可以通过 with_responsible
方法跟踪变更的责任人:
class ApplicationController < ActionController::Base
around_action :use_logidze_responsible, only: %i[create update]
def use_logidze_responsible(&block)
Logidze.with_responsible(current_user&.id, &block)
end
end
禁用临时日志记录
如果你需要临时禁用日志记录,可以使用 without_logging
方法:
Logidze.without_logging do
post.update(title: "Temporary change")
end
典型生态项目
与 Fx 集成
Logidze 可以与 Fx 集成,以便更好地管理数据库模式:
gem "fx", "~> 0.6"
然后运行 Logidze 安装命令:
bundle exec rails generate logidze:install
与分区表集成
Logidze 支持 PostgreSQL 13+ 的分区表,对于 PostgreSQL 11/12,可以使用 after
触发器:
bundle exec rails generate logidze:model Post --after-trigger
通过这些步骤,你可以在你的 Rails 应用中有效地使用 Logidze 来跟踪和管理数据变更历史。
logidzeDatabase changes log for Rails项目地址:https://gitcode.com/gh_mirrors/lo/logidze
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考