I am developing a commercial rental application with Rails 5. It has a fairly simple structure with users, products, and orders with products owned by users who actually create them.
To allow users to manage the "live" stock of their products, a StockMovement model / table was created with a link to the user and stock changes (positive / negative) and date. Thus, we can determine the stock of a certain product for a certain date in terms of "what the user is ready to offer." With a simple query to one table / model, we manage to get the "amount" of shares, which, as it turned out, is the stock of the product.
In addition, we need to consider when an order is placed and confirmed for a specific product, which leads to the need to subtract the quantity of this item from stock for a certain period of time.
Currently, we are calculating the stock with the request in the StockMovement model and manually adding the amounts that are affected by the orders using the custom select clause in the StockMovement model, which is already starting to feel redundant (we are not even beta).
My question is: how would you implement this Rails? I've always had problems with situations where, theoretically, at least considering the relational logic db (we use Postgres), it’s optimal to calculate everything on the fly using queries with joins and calculated fields, but when it comes to implementing using ActiveRecord, there is no way to refer to the computed column in table B in the query for table A unless you redefine this calculation in the select expression in model A, which I am trying to avoid.
So far, my options, which I now see, are as follows:
1- Keep things the way they are: repeat the calculation logic in the select statement to access the "calculated foreign fields"
2- Create an entry in the StockMovement table every time an order is confirmed and processes all stocks from there (IMHO is not desirable, since it needs to be carefully updated every time something changes in orders)
3- A potential magical (and right) decision that I could not think of ...
Thanks!
ruby-on-rails activerecord postgresql calculated-columns
Martí Gascó
source share