0

In my index view of products, I have an "Add to cart" that calls javascript function addToCart:

addToCart: function() {
  $.ajax({type:     'GET',
          url:  'store/add_to_cart/2',    // fixed id of product
      timeout:  5000,
      success:  function() { alert('Added !'); },
      error:    function() { alert('Error !'); }
  });
}



 def add_to_cart  // not working
    begin
      prod = Product.find(params[:id])
      @cart = find_cart
      @cart.add_product(prod)
      render :partial => 'cart', :object => @cart if request.xhr? 
    end
  end

With this add_to_cart, it renders the partial but also renders the default view for this method - add_to_cart.html.haml - But if I do it like the following, it renders only the partial. Could anybody explain me why it is different?

 def add_to_cart    // working fine
    begin
      prod = Product.find(params[:id])
      @cart = find_cart
      @cart.add_product(prod)
      if request.xhr?
        render :partial => 'cart', :object => @cart 
      else
        redirect_to_index    
      end
    end
  end

Thanks for your help !!

Ashis Kumar
  • 6,494
  • 2
  • 21
  • 36

1 Answers1

0

The problem is that in that line rails get's confused where are the params for the render call and where is the statement. You should probably try going like render(:partial => 'cart', :object => @cart) if request.xhr?.

And another thing. If you're using a local variable in the partial, it's better to use locals: {cart: @cart} instead of your :object. Or, if you are following the conventions and that cart partial is in app/view/carts/_cart.html* you can just say render @cart.

Almaron
  • 4,127
  • 6
  • 26
  • 48
  • I tried
    render(:partial => 'cart', :object => @cart) if request.xhr?
    but is the same: renders the partial and the default. Any other idea?
    – Hector Rios Sep 15 '13 at 06:38