Search code examples
ruby-on-railsrubycycle

After loop always nil in Rails 4


When I try cycle the rails array I have still nil, even when array already defined.

The code:

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 have array with three items. abort is there for testing only.

current_user.accounts have:

#<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>]>

account is always nil

currency_obj is:

module HashCurrencible
  extend ActiveSupport::Concern

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

I get this error for row next if not account.currency_obj.coin?, when remove abort:

undefined method `coin?' for nil:NilClass

Solution

  • currenc_obj is nil, so it can't respond to coin? method; check this line:

    #<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
    

    In your first Account object, the attribute :currency is nil so the method currency_obj will return nil as well.