0

我正在使用名为 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

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

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

4

1 回答 1

0

这最终变成了鸡和蛋的问题。无法创建地址,因为它需要一个 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
于 2017-10-25T17:35:46.897 回答