我正在研究一個集成了比特幣API的應用程序,我正在努力使用條件語句,而且我認爲這是由於我對ActiveRecord或SQL方法缺乏瞭解。條件語句幫助和重構Rails
這是所期望的行爲:
- 該API被調用,生成並保存一比特幣地址。
- 需要向用戶顯示相同的比特幣地址,直到付款完成爲止。
- 付款完成後,用戶想再次付款時,需要再次調用API以生成新的比特幣地址。
我已經找到了find_or_create的方法,但我不知道如何使用它在我的實現或方法用說:「如果它不存在 - 這樣做」我有
代碼到目前爲止,如果已有Payment
,但如果沒有現有的Payment
,則會出現無效或未知的方法/變量錯誤。
If a Payment exists, and the last Payment's amount is 0.0 or nil, just show the last Payment's existing Bitcoin address.
if Payment.exists?
Payment.last.amount.to_f == 0.0 && Payment.last.amount == nil
@last_address = Payment.last.btc
@last_address
Then else if the Payment is greater than 0.0 generate and save a new Bitcoin address.
elsif Payment.present?
Payment.last.amount.to_f > 0.0
@new_address = BlockIo.get_new_address
Payment.create(btc: @new_address['data']['address'])
respond_to do |format|
format.html { redirect_to '/save_btc'}
end
Else Just generate and save a new Bitcoin address.
else
@new_address = BlockIo.get_new_address
Payment.create(btc: @new_address['data']['address'])
respond_to do |format|
format.html { redirect_to '/save_btc'}
end
end
我如何重構這個代碼,同時還怎麼用find_or_create或者如果記錄不通過調用存在創造新紀錄API?
用戶不需要在視圖中執行任何操作,因爲一旦他們點擊付費,就會調用運行上述方法的頁面。這是我的路線,它運作得非常好:
match '/save_btc' => 'payments#create', via: [:get, :post]
任何幫助或意見將不勝感激。提前致謝。
編輯:如果沒有現有的支付,我得到以下錯誤:
NoMethodError - undefined method `amount' for nil:NilClass:
從而表現出進行相關的ELSIF行:Payment.last.amount.to_f > 0.0
NoMethodError - undefined method
量」的零:NilClass: 應用/controllers/payments_controller.rb:17:in create' actionpack (5.0.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in
send_action' actionpack(5.0.0.1)lib/abstract_controller/base.rb:188:在process_action' actionpack (5.0.0.1) lib/action_controller/metal/rendering.rb:30:in
process_action' actionpack(5.0.0.1)lib/abstract_controll er/callbacks.rb:20:在block in process_action' activesupport (5.0.0.1) lib/active_support/callbacks.rb:126:in
中調用' activesupport(5.0.0.1)lib/active_support/callbacks.rb:126:在call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:506:in
塊中(2級)編譯' activesupport(5.0.0.1)lib/active_support/callbacks.rb:455:在call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:455:in
調用' activesupport(5.0.0.1)lib/active_support/callbacks.rb:101:在__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in
_run_process_action_callbacks' activesupport(5.0.0.1)lib/active_support/callbacks.rb:90:run_callbacks' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in
process_action' actionpack(5.0.0.1)lib/action_controller/metal/rescue。RB:20:在process_action process_action' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in
塊」 的ActiveSupport(5.0.0.1)的lib/active_support/notifications.rb:164:在block in instrument'
你能發佈你在問題中得到的錯誤的堆棧跟蹤嗎? –
@CdotStrifeVII我已經添加了有關錯誤的其他信息,謝謝。 –