具有可租户嵌套属性的 ActsAsTenant 会导致 ActsAsTenant::Errors::NoTenantSe



我正在管理页面上处理一个名为 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

创建运行时,它包括创建关联地址所需的所有属性。但是,尚未创建地址的租户,因为我们正在构建租户(经销商分支)和关联的租户(地址)。在分配给@dealer_branch的行上,我收到错误

ActsAsTenant::Errors::NoTenantSet: ActsAsTenant::Errors::NoTenantSet

处理此类嵌套属性的正确方法是什么?

这最终变成了一个先有鸡还是先有蛋的问题。尚无法创建地址,因为它需要一个经销商分支,该地址需要属于该地址。父对象 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

相关内容

  • 没有找到相关文章

最新更新