0

我想在我的应用程序中使用 ajax 这是我的问题:

我有一个收入凭证控制器和模型,可以从各种来源获得收入。为此,我有一个带有卡、支票和 internet_banking 付款选项的 payment_mode 模型,这是我的代码:

来自模型: income_voucher

 class IncomeVoucher < ActiveRecord::Base
  has_one :payment_mode, :foreign_key => :voucher_id
 end

** 付款方式:**

class PaymentMode < ActiveRecord::Base
 belongs_to :transactionable, :polymorphic => true
 belongs_to :receipt_voucher    
end

信用卡支付:

class CardPayment < ActiveRecord::Base
  has_one :payment_mode, :as => :transactionable, :dependent => :destroy
end

支票和网上银行的模式类似。

我的控制器: income_vouchers_controller:

class IncomeVouchersController < ApplicationController
def new
    @income_voucher = IncomeVoucher.new
    @invoices = current_company.invoices
    @income_voucher.build_payment_mode

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @income_voucher }
    end
  end
 def create
    @income_voucher = IncomeVoucher.new(params[:income_voucher])

   transaction_type = params[:transaction_type]
    payment_mode = nil
    if transaction_type == 'cheque'
      payment = ChequePayment.new(params[:cheque_payment])
    payment.amount = @income_voucher.amount
    elsif transaction_type == 'card'
      payment = CardPayment.new(params[:card_payment])
    payment.amount = @income_voucher.amount
    elsif transaction_type == 'ibank'
      payment = InternetBankingPayment.new(params[:internet_banking_payment])
    payment.amount = @income_voucher.amount
    else
      payment = CashPayment.new
    payment.amount = @income_voucher.amount
    end
    payment_mode = PaymentMode.new
    payment_mode.transactionable = payment

    @income_voucher.payment_mode = payment_mode
    respond_to do |format|
      if @income_voucher.save

        format.html { redirect_to(@income_voucher, :notice => 'Income voucher was successfully created.') }
        format.xml  { render :xml => @income_voucher, :status => :created, :location => @income_voucher }
      else

        format.html { render :action => "new" }
        format.xml  { render :xml => @income_voucher.errors, :status => :unprocessable_entity }
      end
    end
  end

在我的表格中,我这样做了:

<%= render :partial => "card_payment" %>
<%= render :partial => "cheque_payment" %>
<%= render :partial => "internet_banking_payment" %>

朋友,直到现在,我只是像在 rails 中那样渲染我的局部,但现在我想使用 ajax 来做到这一点。我希望你们早点这样做。谢谢

4

1 回答 1

2

这很简单:

在您的 javascript 中(在页面上,例如:

$.ajax({
  url: "your_path",
  data: {  //params if needed
    your_param_name: param,
    your_param_name2: param2
  }
});

在您的路线中:

match 'your_path' => 'y_controller#y_method'

在 y_controller 中:

def y_method
  # do smth with params[:your_param_name] if needed
  respond_to do |format|
    format.js
  end
end

在您的 y_method.js.erb 中:

$('#your-div').html('<%= raw escape_javascript render("cart_payment") %>'); //instead html() may be append()
于 2012-05-29T11:04:39.623 回答