Rails 6使用PaperTrail如何仅拉取单个Book模型的版本日志
解决方法
PaperTrail 的 versions 表默认携带 item_type 字段,用于存储对应关联模型的类名字符串,你只需在查询版本记录时增加该字段的过滤条件,即可仅拉取 Book 模型的操作日志。
修改后完整代码
def call CSV.generate(col_sep: ';', write_headers: true, headers: LOG_HEADERS, encoding: 'UTF-8') do |csv| # 新增 where(item_type: 'Book') 过滤仅保留Book模型的版本记录 PaperTrail::Version.includes([:item]).where(item_type: 'Book').limit(50).order(id: :desc).each do |v| tracked_data(v) csv << [v.created_at.in_time_zone('CET'), v.event, v.whodunnit, # 修正原代码的笔误:循环变量为v不是version @new_data_value] end end end
额外注意事项
- 若你的
Book模型存在命名空间,需要传入完整类名作为过滤值,例如模型为Admin::Book时,过滤条件需写为where(item_type: 'Admin::Book') - 如果你需要拉取单个指定 Book 实例的操作记录,可以直接调用实例的
versions方法:@book.versions.order(id: :desc).limit(50)
内容的提问来源于stack exchange,提问作者mr_muscle
相关产品推荐
相关产品推荐

