Simple AJAX question

Dear all,

Help me get a simple AJAX behavior right. I know zero AJAX, thus
please advice. Below is a simplification of the real code and I hope I
can describe my intention clearly.

class StoreController < ApplicationController
def show_cart
@cart = Cart.new
@new_item = CartItem.new
end

def add_item
@new_item = CartItem.new(params[:new_item])
if @new_item.valid?
@cart.items << @new_item
# execute add_item.rjs
else
breakpoint
render :partial => ‘new_item’
end
end
end

app/views/store/show_cart.rhtml

Cart contents

<%= render :partial => 'cart', :object => @cart %>
<%= render :partial => 'new_item', :object => @new_item %>

app/views/store/_new_item.rhtml

<%= form_remote_tag :url => { :action => ‘add_item’ } %>
<%= error_messages_for ‘new_item’ %>
<%= text_field ‘new_item’, ‘product_code’ %>
<%= text_field ‘new_item’, ‘quantity’ %>
<%= submit_tag ‘Add Item’ %>
<%= end_form_tag %>

Please remember that the code is chopped in various places but I know
for sure you guys with high Rails-fu skill know the scenario.

The full scenario:

  • I want to hit the breakpoint that I put in StoreController. The
    validations in CartItem have been set to not let @new_item valid.
  • When I hit the breakpoint in StoreController, I manually tipe render
    :partial => ‘new_item’ and Rails is always smart enough to return the
    right partial, complete with the error_messages_for result and
    fieldWithErrors
  • If I remove the breakpoint and start testing with a browser, the
    browser IS NOT refreshing the ‘new-form-item’ div. Why of course!?!

Question is: what is the best way to reload the div thus the user can
see the error messages on their browser? Should I add << :update =>
‘new-item-form’ >> to form_remote_tag argument? This is what I’m
doubting, is it the right way? Is there a better way?

Thanks in advance.

Sincerely,
John