From 434f1a0b8568e242eddade1dd6d70bf02349d88c Mon Sep 17 00:00:00 2001 From: evazion Date: Mon, 12 Aug 2019 19:20:33 -0500 Subject: [PATCH] favorites: fix LockWaitTimeout errors. Favoriting posts sometimes fails with ActiveRecord::LockWaitTimeout errors. This happens when a user tries to favorite multiple posts in short succession. In that case we want the lock to block and wait for the other favorite to go through, not to immediately fail. --- app/models/favorite.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/favorite.rb b/app/models/favorite.rb index d751cee07..efd05bd14 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -7,7 +7,7 @@ class Favorite < ApplicationRecord def self.add(post:, user:) Favorite.transaction do - User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first + User.where(id: user.id).select("id").lock("FOR UPDATE").first if user.favorite_count >= user.favorite_limit raise Error, "You can only keep up to #{user.favorite_limit} favorites. Upgrade your account to save more." @@ -29,7 +29,7 @@ class Favorite < ApplicationRecord post_id = post.id end - User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first + User.where(id: user.id).select("id").lock("FOR UPDATE").first return unless Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post_id).exists? Favorite.for_user(user.id).where(post_id: post_id).delete_all