EricTalv
EricTalv

Reputation: 1049

How to calculate a database field with using other fields?

I have this crypto-application that needs to calculate the current market value of inserted values.

I have DB-Table called Crypto-Items.

Each crypto-item has three fields "Crypto_Currency", "Amount" and "Current market value"

Crypto_currency can be any currency "Bitcoin, Ripple, etc".

The user can insert the Currency and Amount.

Now, when My user inserts their "Currency" and "Amount" and upon pressing create, I would need to do a calculation, I use a Bitfinex API to send the Selected currency to the api and then calculate the return with the amount inserted.

My questions are, where should this calculation be made? How would I access the data being sent such as "Crypto_Currency" or "amount"? How do I set them into the database.

The database in use is PostgreSQL.

My app is fully api based so this is the code to how a Crypto-item is made :

  # POST /crypto_items
  def create
    @crypto_item = CryptoItem.new(crypto_item_params)

    if @crypto_item.save
      render json: @crypto_item, status: :ok
    else
      render json: @crypto_item.errors, status: :unprocessable_entity
    end
  end

Upvotes: 2

Views: 123

Answers (1)

artur.prado
artur.prado

Reputation: 72

Have you considered using a hook?

You can create a before_save in the CryptoItem, something like this:

class CryptoItem < ApplicationRecord
  before_save :do_whatever

  private

  def do_whatever
    # Your calculation goes here.
    # you can assign the result of the Bitfinex API call 
    # to an attribute using self.attribute = ...
  end
end

Upvotes: 1

Related Questions