Reputation: 1529
I'm creating a credit-based application, where the user puts credit in his account and the credit decreases over time based on user's active services.
For example:
I realize that I can use cron jobs to decrease the account balance, but it's gonna make a lot of requests to database and I am sure there must be better ways to do that.
How can I do it?
Upvotes: 0
Views: 160
Reputation: 6121
One way to achieve this is using a column
and a callback
e.g.
You will need to add a column say last_deducted_on
as date
then in the show
action of account_balance
you can have a before_action
like
before_action :deduct_amount_if_applicable, only: :show
private
def deduct_amount_if_applicable
if current_user.deduction_applicable?
amt = (Date.today - account.last_deducted_on).to_i * amount_to_be_deducted
account.update_attribute(:total, (account.total - amt))
# update column with today's date
end
end
Although it will work, I suggest to use scheduler as it is a scheduled job and needs to be done every day, there are ways to reduce queries e.g. using update_all
, etc. depending on use case but still the better option. In case if you have transaction history and you show date of transaction, above method will piss of user if he will open his account days later and suddenly huge amount is deducted.
Upvotes: 1