diff --git a/app/models/user_action.rb b/app/models/user_action.rb index 23c89a89df9..14a448f9667 100644 --- a/app/models/user_action.rb +++ b/app/models/user_action.rb @@ -249,7 +249,29 @@ SQL end def self.synchronize_favorites - + exec_sql(" + DELETE FROM user_actions ua + WHERE action_type = :star + AND NOT EXISTS ( + SELECT 1 FROM topic_users tu + WHERE + tu.user_id = ua.user_id AND + tu.topic_id = ua.target_topic_id AND + starred + )", star: UserAction::STAR) + + exec_sql("INSERT INTO user_actions + (action_type, user_id, target_topic_id, target_post_id, acting_user_id, created_at, updated_at) + SELECT :star, tu.user_id, tu.topic_id, -1, tu.user_id, tu.starred_at, tu.starred_at + FROM topic_users tu + WHERE starred AND NOT EXISTS( + SELECT 1 FROM user_actions ua + WHERE tu.user_id = ua.user_id AND + tu.topic_id = ua.target_topic_id AND + ua.action_type = :star + ) + ", star: UserAction::STAR) + end def self.ensure_consistency! diff --git a/spec/models/user_action_spec.rb b/spec/models/user_action_spec.rb index cdddf7b9613..b4eb5783644 100644 --- a/spec/models/user_action_spec.rb +++ b/spec/models/user_action_spec.rb @@ -262,18 +262,34 @@ describe UserAction do end describe 'synchronize_favorites' do - pending 'corrects out of sync favs' do + it 'corrects out of sync favs' do post = Fabricate(:post) post.topic.toggle_star(post.user, true) + UserAction.delete_all action1 = UserAction.log_action!( action_type: UserAction::STAR, user_id: post.user.id, acting_user_id: post.user.id, - target_topic_id: -1, - target_post_id: post.id, + target_topic_id: 99, + target_post_id: -1, ) + action2 = UserAction.log_action!( + action_type: UserAction::STAR, + user_id: Fabricate(:user).id, + acting_user_id: post.user.id, + target_topic_id: post.topic_id, + target_post_id: -1, + ) + + UserAction.synchronize_favorites + + actions = UserAction.all.to_a + + actions.length.should == 1 + actions.first.action_type.should == UserAction::STAR + actions.first.user_id.should == post.user.id end end