I am following this tutorial to make Cart in my Ecomerce App: https://richonrails.com/articles/building-a-shopping-cart-in-ruby-on-rails Anything do well but when session end and customer do not complete the order, this order and order item still saved in the database. My idea is use callback method before_destroy session cart but i dont know exactly what method destroy session Can anyone help me?
Unfortunately the callback method will be difficult, because you never know when the session ended, since websites are stateless. In other words, you never really know whether a visitor is just idle, or he actually left. The only signs you normally get, are requests (GET/POST/PATCH/..).
What you could do to make this work, is check the last_updated value, and delete all non-confirmed carts after let's say two hours. Or, you could even do a day, because who cares right? It's only a few bytes in your DB.
To make this work, you could write a rake task that queries and deletes all the abandoned carts.
Something like:
# cart model
class Cart
scope :unconfirmed { where(bought: false) }
scope :abandoned, { unconfirmed.where('last_update < ?', 1.day.ago}
end
# rake task
namespace :maintenance do
task delete_abandoned_carts: :environment do
Cart.abandoned.destroy_all
end
end
Learn more about rake tasks here: https://guides.rubyonrails.org/command_line.html#custom-rake-tasks