简体   繁体   English

Rails:远程:从select_tag为true

[英]Rails: remote: true from select_tag

I'm calling an AJAX function from a select_tag like so: 我正在从select_tag调用AJAX函数, select_tag所示:

<%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %>

And here's the function: 这是函数:

<script type='text/javascript'>
  function update_price(order_id, quantity) {
    $.ajax({
      url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
      type: "POST",
      data: {
        "order_id" : order_id,
        "quantity" : quantity },
      dataType: "html"
    });
  }
</script>

My .js.erb isn't called ever, and I suspect it's because I haven't specified remote: true anywhere, but since I don't have a form per se I don't know how to do that. 我的.js.erb被调用过,我怀疑这是因为我没有指定remote: true在任何地方都remote: true ,但是由于我本身没有表单,所以我不知道该怎么做。 Any help? 有什么帮助吗?

Relevant controller code here: 此处的相关控制器代码:

class CartTransactionsController < ApplicationController
  load_and_authorize_resource

  respond_to :html, :js

  before_filter :set_cart_transaction

  def update_quantity
    @order = @cart_transaction.orders.find(params[:order_id])
    @price = current_user.brand.prices
                         .where(template_id: @order.document.template.id)
                         .where(quantity: params[:quantity]).first
    @order.update_attributes(
      price_cents: @price.amount_cents, quantity: params[:quantity]
    )
    @cart_transaction.save!
    respond_to { |format| format.js }
  end

  private

  def set_cart_transaction
    @cart_transaction = current_user.cart
  end

  def cart_transactions_params
    params.require(:cart_transaction).permit(
      :name, :email, :delivery_address, :comments
    )
  end
end

Update 更新资料

Here's the .js.erb that isn't called for some reason: 这是由于某种原因未调用的.js.erb

console.log("update_quantity.js.erb file");

$('#price_cell').html("<%= j render(partial: 'price', locals: { order: @order }) %>");
$('#subtotals').html("<%= j render(partial: 'subtotals', locals: { cart_transaction: @cart_transaction }) %>");

Try this: 尝试这个:

function update_price(order_id, quantity) {
    $.ajax({
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
      },
      url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
      type: "POST",
      data: {
        "order_id" : order_id,
        "quantity" : quantity }
    });
  }

使用dataType:“ script”,它将工作并呈现js.erb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM