2017-10-20 9 views
0

DealerBranch라는 모델과 Address라는 tenanted nested association이라는 응용 프로그램의 관리 페이지에서 작업하고 있습니다. 이 필요한 모든 속성을 포함하고 실행을 만들Tensable 중첩 된 특성을 가진 ActsAsTant는 ActsAsTenant :: Errors :: NoTenantSet을 발생시킵니다. ActsAsTenant :: Errors :: 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가 아직 저장되지 않았습니다. 일할 수있는 중첩 위해서는 내가 먼저 DealerBranch을 저장 그것을 아래로 나누기 create_with_address 방법 작성 :

# 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