6

我已经审核(以前为acts_as_audited)设置和工作。user_id 已成功保存在审计表中,但我无法找到保存tenant_id 的有效方法(我有带范围的多租户设置)。我曾尝试使用自述文件中描述的关联审计技术,但这对我不起作用。

我目前的解决方案是在每个模型中使用after_audit回调(可以用 Rails 关注点实现)来获取最后的审计并保存tenant_id:

def after_audit
  audit = Audit.last
  audit.tenant_id = self.tenant_id
  audit.save!
end

虽然这可行,但必须再次查询审计然后更新它似乎效率低下。在保存之前将tenant_id添加到审计中对我来说更有意义,但我不知道如何做到这一点。是否可以在保存之前将tenant_id添加到审核中?如果是,那么如何?

编辑:

我也尝试在我的审计模型中包含我的默认租户范围,但它似乎没有被调用:

审计.rb

class Audit < ActiveRecord::Base
 default_scope { where(tenant_id: Tenant.current_id) }

application_controller.rb

class ApplicationController < ActionController::Base
  around_action :scope_current_tenant

  def scope_current_tenant
    Tenant.current_id = current_tenant.id
    yield
  ensure
    Tenant.current_id = nil
  end

编辑:2/1/16

我仍然没有对此实施解决方案,但是我目前的想法是使用:

#model_name.rb
  def after_audit
    audit = self.audits.last
    audit.business_id = self.business_id
    audit.save!
  end

在这段代码中,我们得到了当前模型的最后一次审计。这样我们只处理当前模型,没有机会将审计添加到另一个业务(据我所知)。我会将此代码添加到关注点中以使其保持干燥。

我仍然无法让正常的 Rails 回调在 Audit 模型中工作。我目前看到的唯一另一种方法是分叉和修改 gem 源代码。

4

2 回答 2

2

我的任务是实施审计,并添加对组织的引用。迁移添加了这一行:

t.references :org, type: :uuid, index: true, null: true

为了保存 org_id,我最终编写了一个初始化程序 - audited.rb。该文件如下所示:

Rails.configuration.after_initialize do
  Audited.audit_class.class_eval do
    belongs_to :org, optional: true

    default_scope MyAppContext.context_scope

    before_create :ensure_org

    private

    def ensure_org
      return unless auditable.respond_to? :org_id

      self.org_id = auditable.org_id
    end
  end
end

希望这可以帮助!

于 2020-02-10T18:14:59.633 回答
1

我最近将 Acts As Tenant gem 添加到运行 Audited gem 的 Rails 应用程序中。我遇到了同样的问题。我添加了

acts_as_tenant :account

审计模型,但它没有做任何事情。我了解到您不能在审计模型中覆盖,而必须创建一个从它继承的自定义审计模型。所以我创建了模型:custom_audit.rb

class CustomAudit < Audited::Audit
  acts_as_tenant :account
end

然后我在confi/initializers中添加了初始化文件audited.rb,如下所示:

Audited.config do |config|
  config.audit_class = CustomAudit
end

除了 show_audit 视图之外,我的所有多租户都在工作的问题仍然存在。我终于在我的测试设置中删除了两个租户的所有审计。有效!我现在可以添加新的审计,它们的范围很好。但是我仍然需要将实际的客户端数据库合并为一个,并且我不想丢失审计表中的历史记录......不知道如何解决这个问题。

因此,当我尝试访问审核时,它会因 current_tenant 为 nil 而失败。不知道为什么删除表中的所有当前记录会修复它,但我需要找到解决方法。

于 2021-08-29T18:58:34.660 回答