问题
I'm working on a Rails 3 shopping cart. I've a catalog page that displays all products and one partial that gives a gist of the shopping cart. So whatever product a user adds to the cart is displayed in this shopping cart partial. Now, this ain't working. I've to hit refresh after adding a product to cart, otherwise the partial doesn't update.
Here's my code:
Cart_Controller add method
def add
@cart = user_cart
@deal = Deal.find(params[:id])
@item = @cart.add(params[:id])
flash[:notice] = "Added #{@deal.deal_name} to cart"
@cart = user_cart
respond_to do |format|
format.html{ redirect_to root_path}
format.js
end
add.js.erb
$("#shopping_cart").replace_html("<%=escape_javascript(render(:partial => 'cart', :locals => {:cart => @cart}))%>");
Products page
<div id="shopping_cart">
<%=render :partial => 'cart/cart',
:locals => {:cart => user_cart}%>
<%end%>
</div>
<%=link_to "Add to Cart",{:action => 'add', :id => deal.id}, :remote => true%>
This is what I see in my logs:
Started GET "/cart/add/2" for 127.0.0.1 at 2011-07-02 18:04:38 -0700
Processing by CartController#add as JS
Parameters: {"id"=>"2"}
Rendered cart/_cart.html.erb (9.6ms)
Rendered cart/add.js.erb (11.7ms)
Completed 200 OK in 274ms (Views: 23.4ms | ActiveRecord: 0.0ms)
Please help me with this.
回答1:
Try
$("#shopping_cart").html("<%= escape_javascript(render(:partial => 'cart', :locals => {:cart => @cart})).html_safe %>");
来源:https://stackoverflow.com/questions/6560592/rails-3-ajax-update-partial-doesnt-work-without-page-refresh