2011-06-26 92 views
3

我試圖讓我的路由在更新發票後正常工作。Rails3嵌套的路線,更新重定向到問題

我有很多發票的訂單,並在我的routes.rb

resources :orders do 
resources :invoices 
end 

resources :invoices 

而在我的發票控制器如下:

def update 
    @invoice = Invoice.find(params[:id]) 
    respond_to do |format| 
     if @invoice.update_attributes(params[:invoice]) 
     format.html { redirect_to(invoice_path(@invoice), :notice => 'Invoice was successfully updated.') } 
     else 
     format.html { render :action => "edit" } 
     end 
    end 
    end 

我可以創建通過發票:

/orders/1/invoices/new 

但是當我保存或更新時,我發送到:

/invoices/1 

我要回重定向到訂單發票路徑:

/orders/1/invoices/1 

也試圖改變重定向到:

redirect_to(order_invoice_path(@order, @invoice), :notice => 'Invoice was successfully updated.') 

這工作,但它向我發送了錯誤的網址訂單ID與發票ID相同...

任何幫助表示讚賞。

- 更新 -

如果我嘗試在我的發票控制器下面,我結束了一個錯誤太..

redirect_to(order_invoice_path(@order, @invoice) 

No route matches {:action=>"show", :controller=>"invoices", :order_id=>nil, :id=>#<Invoice id: 6, order_id: 17, invoice_id: nil, created_at: "2011-06-26 17:49:01", updated_at: "2011-06-26 17:49:01">} 

回答

2

看來你做的以下在您的控制器中:

redirect_to(order_invoice_path(@order, @invoice), :notice => 'Invoice was successfully updated.') 

Bu你是否在某個地方設置了@order

不管結果如何,你最好這樣做:

redirect_to(order_invoice_path(@invoice.order, @invoice), :notice => 'Invoice was successfully updated.') 
+0

您好,感謝了很多。後一種方法是完美的。我在哪裏可以讀到這一點 - 這真的讓我難以忍受 - 我一直在試圖弄清楚要做這樣的事情。 Jx –

+0

當您在模型之間創建關聯時,這種方法是內置的:http://guides.rubyonrails.org/association_basics.html – apneadiving