我是 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'