2017-05-24 6 views
0

私はレール配列をサイクルしようとすると、配列が既に定義されていても、まだnilがあります。ループの後にRails 4で常に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常にnilです:

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 
+0

あなたのユーザーとアカウントのモデルとエラーが表示されますか?あなたはどこにいませんか? –

+0

もちろん、 – Maximi

+0

は 'current_user.accounts [0]'または '@ account' nilという質問を更新しましたか? – AlexN

答えて

1

currenc_objnilなので、coin?の方法には対応できません。このラインチェック:あなたの最初のAccountオブジェクトで

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

を、属性:currencyはそれほど方法currency_objも同様nilを返しますnilです。

1

可変アカウントにはループのスコープしかありません。だから、それはループの外側にはありません。

+0

あなたは本当だと思われますが、この問題を解決するには? – Maximi

+1

実際に何が必要なのかによって関数が分かるので、nilの変数を外に宣言してアカウントを割り当てることができます。すべてのアカウントで空の配列を作成し、acoountをループ内に入れたい場合は – Charles

+0

I thoght that thoght account.currency_obj.coinはコインをCurrency.find_by_code(属性[:currency])に注入しますが、そうでない場合は、その方法を教えてください。 – Maximi

関連する問題