私はレールを初めて使用し、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'