当前位置: 动力学知识库 > 问答 > 编程问答 >

conditional - if/else in controller and view Rails

问题描述:

I have an app that I am integrating Bitcoin into using BlockIo API. When a user wants to make a payment, a new Bitcoin address is created for them and saved on the db, and after they make a payment the the amount is also saved, and that amount is retrieved from the API. I need assistance with the syntax or proper way to get the conditional statement working.

To generate and save a new Bitcoin address in the controller the code is:

@new_address = BlockIo.get_new_address

Payment.create( btc: @new_address['data']['address'] )

I want to create a conditional statement that will display the already generated bitcoin address if the amount (amount:) of the last Payment (Payment.last) is <= '0.00000000' || == nil, else generate a new address.

The attributes for the Payment model/controller are bitcoin:string and amount:string

Update: The below code works, but first displays @last_address and then upon refresh displays the newly generated address in the view.

def create_address

@last_address = Payment.last.bitcoin

@last_amount = Payment.last.amount

if @last_amount == '0.00000000' || @last_amount == nil

@last_address

else

@new_address = BlockIo.get_new_address

Payment.create( btc: @new_address['data']['address'] )

end

end

But the above code is not working, as it does not generate a new address when I update last Payments' amount to a bigger amount via console.

Please advise on how I can better the below code to get the desired result:

Send your Bitcoins to:

<% if @last_address %>

<strong><%= @last_address %></strong><br>

<%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=#{@last_address}" %>

<% else %>

<strong><%= @new_address['data']['address'] %></strong><br>

<%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=#{@new_address["data"]["address"]}" %>

<% end %>

Update: Please advise if my view code is correct, as I still first see the "old" @last_address and need to refresh to see the actual new generated @last_address.

网友答案:

I have managed to get it to work the way I want although it still feels a bit hacky as I have made sure that the page refreshes after the new address is saved, thus only displaying the latest saved address.

def create_address
  @last_address = Payment.last.bitcoin
  @last_amount = Payment.last.amount

  if @last_amount == '0.00000000' || @last_amount == nil
    @last_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
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: