如何使用ajax在rails 3.0中渲染部分?

时间:2012-05-29 09:40:29

标签: ruby-on-rails-3 jquery

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

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

来自型号: 的 income_voucher

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

** payment_mode:**

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

card_payment:

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" %>
朋友到现在为止我只是像在轨道中那样渲染我的部分,但现在我想用ajax来做这件事。我希望你们早点做到这一点。 谢谢

1 个答案:

答案 0 :(得分: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()