Rails3嵌套路由,更新Redirect_To问题

时间:2011-06-26 18:38:09

标签: ruby-on-rails-3

我正在尝试在更新发票后让我的路由正常工作。

我在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">}

1 个答案:

答案 0 :(得分:2)

您似乎在控制器中执行以下操作:

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

但你在某处设置了@order吗?

无论如何,你最好这样做:

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