具有可租用嵌套属性的 ActsAsTenant 导致 ActsAsTenant::Errors::NoTenantSet:ActsAsTenant::Errors::NoTenantSet

ActsAsTenant with tenantable nested attributes causes ActsAsTenant::Errors::NoTenantSet: ActsAsTenant::Errors::NoTenantSet

我正在处理一个应用程序的管理页面,该应用程序具有一个名为 DealerBranch 的模型和一个名为 Address 的租户嵌套关联。我有一个看起来像这样的控制器,用于创建新的经销商分支:

class Admin::DealerBranchesController < Admin::AdminApplicationController
  def create
    @dealer_branch = DealerBranch.new(dealer_branch_attributes)
    if @dealer_branch.save
      render :success
    else
      render :new
    end
  end
end

创建运行时,它包含创建关联地址所需的所有属性。但是,地址的租户尚未创建,因为我们正在构建租户 (DealerBranch) 和关联的租户 (Address)。在分配给@dealer_branch 的那一行,我收到错误 ActsAsTenant::Errors::NoTenantSet: ActsAsTenant::Errors::NoTenantSet

像这样处理嵌套属性的正确方法是什么?

这最终变成了先有鸡还是先有蛋的问题。无法创建地址,因为它需要一个 DealerBranch,地址需要属于该地址。父对象 DealerBranch 尚未保存。为了使嵌套工作,我创建了一个 create_with_address 方法,该方法将其分解以首先保存 DealerBranch:

  # We need this method to help create a DealerBranch with nested Address because address needs DealerBranch
  # to exist to satisfy ActsAsTenant
  def self.create_with_address(attributes)
    address_attributes = attributes.delete(:address_attributes)
    dealer_branch = DealerBranch.new(attributes)

    begin
      ActiveRecord::Base.transaction do
        dealer_branch.save!
        ActsAsTenant.with_tenant(dealer_branch) do
          dealer_branch.create_address!(address_attributes)
        end
      end
    rescue StandardError => e
      if dealer_branch.address.nil?
        # rebuild the attributes for display of form in case they were corrupted and became nil
        ActsAsTenant.with_tenant(dealer_branch) { dealer_branch.build_address(address_attributes) }
      end

      unless dealer_branch.valid? && dealer_branch.address.valid?
        return dealer_branch
      else
        raise e
      end
    end

    dealer_branch.reload
  end