在Rails 4中循环后总是nil

时间:2017-05-24 11:52:28

标签: ruby-on-rails ruby cycle

当我尝试循环rails数组时,我仍然为nil,即使已经定义了数组。

代码:

def gen_address
  current_user.accounts.each do |account|
    abort(@account.inspect)
    next if not account.currency_obj.coin?

    if account.payment_addresses.blank?
      account.payment_addresses.create(currency: account.currency)
    else
      address = account.payment_addresses.last
      address.gen_address if address.address.blank?
    end
  end
  render nothing: true
end

current_user.accounts包含三个项目的数组。中止仅用于测试。

current_user.accounts有:

#<ActiveRecord::Associations::CollectionProxy [#<Account id: 14, member_id: 3, currency: nil, balance: 0.0, locked: 0.0, created_at: "2017-05-23 08:50:11", updated_at: "2017-05-23 08:50:16", in: nil, out: nil, default_withdraw_fund_source_id: nil>, #<Account id: 5, member_id: 3, currency: "btc", balance: 0.0, locked: 0.0, created_at: "2017-05-03 08:37:19", updated_at: "2017-05-03 08:37:19", in: nil, out: nil, default_withdraw_fund_source_id: nil>, #<Account id: 6, member_id: 3, currency: "ltc", balance: 0.0, locked: 0.0, created_at: "2017-05-03 08:37:19", updated_at: "2017-05-03 08:37:19", in: nil, out: nil, default_withdraw_fund_source_id: nil>, #<Account id: 13, member_id: 3, currency: "eth", balance: 0.0, locked: 0.0, created_at: "2017-05-23 08:42:29", updated_at: "2017-05-23 08:42:35", in: nil, out: nil, default_withdraw_fund_source_id: nil>]>

帐户始终为零

currency_obj是:

module HashCurrencible
  extend ActiveSupport::Concern

  included do
    def currency_obj
      Currency.find_by_code(attributes[:currency])
    end
  end
end

如果不是account.currency_obj.coin,我会在下一行收到此错误,当删除中止时:

undefined method `coin?' for nil:NilClass

2 个答案:

答案 0 :(得分:1)

变量帐户只有循环范围。所以在循环之外它将是零。

答案 1 :(得分:1)

currenc_objnil,因此无法回复coin?方法;检查这一行:

#<Account id: 14, member_id: 3, currency: nil, balance: 0.0, locked: 0.0, created_at: "2017-05-23 08:50:11", updated_at: "2017-05-23 08:50:16", in: nil, out: nil, default_withdraw_fund_source_id: nil

在您的第一个Account对象中,属性:currencynil,因此方法currency_obj也将返回nil