2013-03-20 3 views
0

내 rails3.2 응용 프로그램에 양식이 있으며이 또한 새로운 회사와 지점을 동시에 작성합니다. 그 모든 잘 작동하지만 지점 테이블에 외래 키 company_id 같이 회사 ID를 저장하고 싶습니다.레일이있는 중첩 된 양식

이 내 불만 컨트롤러 :

def new 
    @complaint = Complaint.new 
    @complaint.build_company 
    @complaint.build_branch(:company_id => '#Trying to set the company ID here') 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @complaint } 
    end 
    end 

내가 위에서 만든 개체의 ID를 할당 할 :company_id => 후 넣을 수 있습니다 무엇입니까?

+0

내가이 일을'after_create' 행동의 어떤 종류가 필요하십니까 활동 작성에 다음 코드를 추가했다? – pjmil

+0

accepts_nested_attributes_for 및 중첩 된 양식을 사용하여 보셨습니까? –

답변

0

이처럼 좋지 않을까요?

@complaint.build_branch(:company_id => @complaint.company_id) 
+0

'@ complaint.company'도 같은 요청으로 작성된 새로운 레코드이기 때문에 이것이 작동하지 않습니다. – jvnill

+0

그건 작동하지 않습니다, 그것은 여전히 ​​NULL 값을 저장합니다. – pjmil

+0

저장되지 않은 인스턴스의 빌드로 외래 키를 설정할 수 없습니다. 저장시 덮어 씁니다. –

0

문제는 저장하지 않은 회사 개체 & 불만 사항으로 인한 것 같습니다. 당신은 모델에 대한 세부 사항을 설명하지 않은,하지만 내 생각,

@complaint = Compplaint.create(#Whatever parameters are required) 
company = @complaint.companies.create() #Assuming has_many relationship 
@complaint.branches.create(:comapny_id => company.id) 

레코드를 저장하고 ID를 생성하고 생성, 어디 구축으로 새로운하지 않습니다.

또한 모델에서 has_many : through를 탐색해야합니다.

0

이 솔루션은

def create 
... 
@complaint.branch.company = @complaint.company 
@complaint.save 
... 
end