0

我是 Rails 新手,无法使用 ajax 在我的模式中设置变量!我的方法是;我首先将它从外部 javascript(jquery 对话框)传递给我的控制器,然后作为参数传递给我的模型方法。请批评!

我的javascript(jquery-dialog按钮中的ajax):

click: function() {
    var qtySelected = $("#quantity[data-id='" + prodvarid + "'] input").val();//inputValue check
    qtySelected = parseInt(qtySelected); //ensure value is int
    $.ajax({
        type: "POST",
        url: '/line_items',
        beforeSend: function(xhr){
             xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        data: {product_id: prodvarid, qty_selected: qtySelected, remote: true},
        dataType: "script"
    });
    alert("input value is: " + qtySelected); //inputValue check
    $("#quantity[data-id='" + prodvarid + "'] input").val(1); //reset default value on submit
    $(this).dialog("close");
}

我的控制器 - 它通过 ajax POST 接收 :qty_selected 值,并使用 ctlQty 将其传递到我的模型中:

# POST /line_items
# POST /line_items.json
def create
 @cart = current_cart
 product = Product.find(params[:product_id])
 ctlQty = :qty_selected
 @line_item = @cart.add_product(product.id, ctlQty)

 respond_to do |format|
 if @line_item.save
  format.html { redirect_to(store_index_url) }
  format.js   { @current_item = @line_item }
  format.json { render json: @line_item, status: :created, :location => @line_item }
  else
   format.html { render :action => "new" }
   format.json { render json: @line_item.errors, status: :unprocessable_entity }
  end
 end
 end

我的模型接收值并设置局部变量 current_qty:

def add_product(product_id, qty_selected)

current_qty = qty_selected
if current_qty
    current_qty = qty_selected
else
    current_qty = 1
end

current_item = line_items.find_by_product_id(product_id)
if current_item
    current_item.quantity += current_qty
else
    current_item = line_items.build(:product_id => product_id)
end
current_item
end

经过测试,我收到:

"TypeError (:qty_selected can't be coerced into Fixnum)"
app/models/cart.rb:17in '+'
app/models/cart.rb:17in 'add_product'
app/controllers/line_items_controller.rb:48in 'create'
4

1 回答 1

0

错误消息表明您正在尝试使用符号和数字。实际上,在控制器中,它应该是:

ctlQty = params[:qty_selected].to_i   # instead of ctlQty = :qty_selected

此外,在 中add_product,前 6 行看起来很复杂,可以简单地写成

current_qty = qty_selected || 1
于 2013-09-24T20:10:03.497 回答