开发者

Rails3 Update Action Problem Nested Resource

I've got an problem with my update action for a nested resource.

In my app, my orders have many invoices.

Creating a new invoice, I correctly end up with the following url:

/orders/11/invoices/new

And when I edit the invoice, again, it's all correct:

/orders/11/invoices/3/edit

This works fine when the save is a success, however if the validation fails, it routes back to:

/invoices/3

I have the following in my invoices controller:

def update
   # @order = Order.find(params[:order_id])
   # @invoice = @order.invoices.find(params[:id])
    @invoice = Invoice.find(params[:id])

    respond_to do |format|
      if @invoice.update_attributes(params[:invoice])
        format.html { redirect_to(order_invoice_path(@invoice.order, @invoice), :notice => 'Invoice was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @invoice.errors, :status => :unprocessable_entity }
      end
    end
  end

def edit
    @invoice = Invoice.find(params[:id])
    3.times { @invoice.invoice_items.build }
  end

I'm assuming I need to edit the @invoice.errors part but I don't know what to chan开发者_JS百科ge it to?

Any help appreciated. Jx


When updating failed, you use "render" (comparing with the "redirect_to" in the succeeding path), this brings you to invoice editing path by default. You can use "redirect_to" here to keep the URI path you want, but need remembering to preserve the models' states so your users don't need to fill the entire form all over again.

A detail instruction can be found here: How to make a render :edit call show the /edit in the address bar

Yan


in your form you should add your order, like this:

<%= form_for [@order, @invoice] ... do |f| %>
  ...
<% end %>

And then uncomment this two lines

# @order = Order.find(params[:order_id])
# @invoice = @order.invoices.find(params[:id])

so your form will send its request to POST /orders/XX/invoices/XX

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜