【问题标题】:render :partial not working as expected渲染:部分未按预期工作
【发布时间】:2013-09-15 06:20:49
【问题描述】:

在我的产品索引视图中,我有一个调用 javascript 函数 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

使用这个 add_to_cart,它会渲染部分视图,但也会渲染此方法的默认视图 - add_to_cart.html.haml - 但是如果我像下面那样做,它只会呈现部分。 谁能解释一下为什么不一样?

 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

感谢您的帮助!!

【问题讨论】:

    标签: ruby-on-rails-4 renderpartial


    【解决方案1】:

    问题在于,在那条线轨中,渲染调用的参数在哪里,语句在哪里,让人感到困惑。 你可能应该尝试像render(:partial => 'cart', :object => @cart) if request.xhr?。

    还有一件事。如果您在局部变量中使用局部变量,最好使用locals: {cart: @cart} 而不是:object。或者,如果您遵循约定并且 cart partial 在 app/view/carts/_cart.html* 中,您可以直接说 render @cart。

    【讨论】:

    • 我尝试了
      render(:partial => 'cart', :object => @cart) if request.xhr?
      但相同:渲染部分和默认值。还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多