2017-10-20 37 views
0

我正在为名为DealerBranch模型的应用程序的管理页面和称为地址的租用的嵌套关联。我有一个控制器,它看起来像这样创建一个新的经销商分支:使用Tenantable嵌套属性ActsAsTenant导致ActsAsTenant ::错误:: NoTenantSet:ActsAsTenant ::错误:: NoTenantSet

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)和相关租借(地址)。在分配到@dealer_branch的行上,我得到错误ActsAsTenant :: Errors :: NoTenantSet:ActsAsTenant :: Errors :: NoTenantSet

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

+0

发布相关的型号代码,你可能会想读这个,如果你还没有的http:// api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html –

回答

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