2

我将 ActiveMerchant 与 Authorize.net 一起使用,并且已经设置了 2 个模型 Order 和 Transaction。(http://railscasts.com/episodes/145-integrating-active-merchant

如果发生错误,我想从事务中获取错误消息,然后在闪存消息中输出。这是我的代码:

#order_controller.rb

  def create
    @order = Order.new(params[:order])

    respond_to do |format|
      if @order.save
        if @order.purchase
          format.html { redirect_to(@order, :notice => 'Order was successfully created.') }
          format.xml  { render :xml => @order, :status => :created, :location => @order }
        else  
          flash[:error] = @order.transactions.response
          format.html { render :action => "new" }
        end 
      else  
        format.html { render :action => "new" }
        format.xml  { render :xml => @order.errors, :status => :unprocessable_entity }
      end
    end
  end

这是我的交易模型:

#models/order_transaction.rb
class OrderTransaction < ActiveRecord::Base
  belongs_to :order
  serialize :params

  def response=(response)
    self.success       = response.success?
    self.authorization = response.authorization
    self.message       = response.message
    self.params        = response.params
  rescue ActiveMerchant::ActiveMerchantError => e
    self.success       = false
    self.authorization = nil
    self.message       = e.message
    self.params        = {}
  end
end

交易数据已保存到数据库中,如下所示:

#models/order.rb
class Order < ActiveRecord::Base
  has_many :transactions, :class_name => "OrderTransaction"
  attr_accessor :card_type, :card_number, :card_month, :card_year, :card_verification

  def purchase
      response = GATEWAY.purchase(charge_amount, credit_card, purchase_options)
      transactions.create!(:action => "purchase", :amount => charge_amount, :response => response)
      response.success?
  end


...
end

我想在交易失败时闪现这个交易错误信息。如果我的一个订单有 2 笔交易,我应该怎么做才能得到这些错误。?

任何帮助将非常感激。

谢谢!

4

0 回答 0