0

所以我按照这个平衡支付教程,并尝试调整他们的支付模型以适应我的应用程序。

原来的:

class Payment

  def initialize(email, amount, credit_card_hash)
    @email = email
    @amount = (amount * 100).to_i
    @credit_card_hash = credit_card_hash
    @buyer = nil
    @card = nil
    @errors = []
  end

end

我的简化版(更新了完整模型的代码):

require 'balanced'

class Transaction < ActiveRecord::Base

  attr_reader :errors, :amount

  def initialize(amount)
    @amount = (amount * 100).to_i
    @buyer = nil
    @card = nil
    @errors = []
  end

    def charge
      begin
        find_or_create_buyer
        debit_buyer
        credit_owner
        return true
      rescue
        return false
      end
    end

  private    

  def find_or_create_buyer
      begin
        @buyer = current_user.balanced_customer
      rescue
        @errors << 'Your account is invalid'
      end
  end

  def debit_buyer
    begin
      payment = @buyer.debit(@amount, "Test transaction")
    rescue
      @errors << 'Your credit card could not be charged'
    end
  end

  def credit_owner
    begin
      Balanced::Marketplace.my_marketplace.owner_account.credit(amount)
    rescue
      @errors << 'Your credit card payment did not go through.'
    end
  end


end

问题是,每次我尝试从 rails 控制台实例化类时,我都会遇到一个纯粹的 ruby​​ 错误,

> payment = Transaction.new(0.01)
 output error: #<NoMethodError: undefined method `has_key?' for nil:NilClass>

我用谷歌搜索了一下,并没有找到一个好的答案。

有任何想法吗?

4

2 回答 2

2

在活动记录中,初始化是使用属性哈希完成的,并且您正在覆盖初始化程序

http://blog.hasmanythrough.com/2007/1/22/using-faux-accessors-to-initialize-values

于 2013-12-01T22:01:28.667 回答
1

好吧,这似乎停止了错误,不管我做了什么。

不确定这是否会在以后引起任何问题,我们将拭目以待。

  def initialize(args = {})
    super
    @my_cache = {}
    @amount = args[:amount]
    @buyer = nil
    @card = nil
    @errors = []
  end
于 2013-10-12T00:36:14.993 回答