2012-06-15 5 views
0

저는 RoR의 초보자이며 일부 모델 작업에 문제가 있습니다.Ruby on Rails - HABTM - 하나의 컨트롤러에서 두 모델에 데이터 삽입

기본적으로 제품 티켓 예약 간에는 habtm 관계가 있습니다. 티켓을 통한 제품 habtm 예약 및 티켓 구매를 통한 제품 habtm 예약.

나는 또한 has_many : products 및 has_many : reservations가있는 Supplier가 있습니다.

내가 원하는 것은 사용자가 공급 업체를 선택하고 제품을 본 후에 해당 공급 업체에서 원하는 제품을 선택할 수 있습니다.

그 예약. 내가 양식을 가지고 있지만 "제출"작업 후 2 모델에 데이터를 삽입해야하므로 문제가 있습니다.

예약을 만들 때 예약 항목과 티켓 항목을 동시에 생성해야하는데 티켓 항목에는 reservation_id와 product_id가 외래 키로 포함됩니다.

내 예약 '보기 :

<%= form_for(@reservation) do |f| %> 

Reservation Info 
<div id="reservation_top"></div> 
<div id="reservation"> 

<%= f.label :name %><br /> 
<%= f.text_field :name %> 

<%= f.label :surname %><br /> 
<%= f.text_field :surname %>    

(...) 

<%= f.hidden_field :supplier_id, :value => @reservation.supplier_id %> #to get the supplier ID 

Products: 

<%= f.fields_for :tickets do |t| %>  
<%= t.select("product_id",options_from_collection_for_select(@products, :id, :name))%> 

#I also have another t.select and although this isn't my primary concern, I wanted this t.select option's to change according to what is selected on the previous t.select("product_id"). Something like a postback. How is it done in RoR? I've searched and only found observe_field, but I didn't understand it very much, can you point me in the right direction? thanks 

<%end%> 

<%= f.label :comments %> 
<%= f.text_area :comments %> 

<%= f.submit%> 

<%end%> 

지금 내가 문제가 내 컨트롤러에 생각하지만, 내가 거기에 넣어 무엇을 이해할 수 없다, 나는 현재하고 있습니다

def new 
    @supplier=Supplier.find(params[:supplier_id]) 
    @reservation = Reservation.new(:supplier_id => params[:supplier_id]) 

    @ticket = Ticket.new(:reservation_id => params[@reservation.id]) 

    @products = Supplier.find(params[:supplier_id]).products 
    @ticket = @reservation.tickets.build 

    respond_to do |format| 
      format.html 
      format.json { render :json => @reservation } 
    end 
    end 


def create 
    @reservation = Reservation.new(params[:reservation]) 

    respond_to do |format|    
     if @reservation.save 
     @reservation.tickets << @ticket 

     format.html { redirect_to @reservation, :notice => 'Reservation Successful' } 
     else 
     format.html { render :action => "new" } 
     format.json { render :json => @reservation.errors, :status => :unprocessable_entity } 
    end 
    end 

나' 지금받는 중

Called id for nil, which would mistakenly be 4 

티켓을 만들려고하고 있어도 reservation_id가 없나요?

전에 habtm 연관을 한 번도 다루지 않았습니다. 어떤 팁? 사전에

감사합니다, 감사합니다

답변

1

가 로그에 생성 동작에 대한 POST의 PARAMS를 살펴 보자. 그러면 데이터를 저장해야 할 때 params에서 어떤 데이터를 사용해야하는지 정확히 알 수 있습니다.

def create 
    @reservation = Reservation.new(params[:reservation]) 
    respond_to do |format| 
    if @reservation.save 
     @reservation.tickets << @ticket 

그 시점에서 @ticket은 무엇

에서

? (믿을 수 없음)

응답을 생성하기 전에 새로운 방법에서 @reservation 및 @ticket이 어떻게 보이는지 흥미 롭다고 생각합니다. 해당 개체 각각에 대해 .inspect를 기록하십시오 당신이 가진 생각을 확실히하기 위해서.

당신이 가진 것처럼 더 복잡한 저장에서는 트랜잭션으로 모두 감쌀 것입니다.