From d417907f368ca8c809921b9f0198e2751abbc588 Mon Sep 17 00:00:00 2001 From: Nicolas Bouilleaud Date: Fri, 7 Jun 2019 14:59:14 +0200 Subject: [PATCH] Just rely on the constraints to avoid duplicate Follows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Don’t check manually in advance: just try to create the new Follow and silently fail. Since we have both Rails validation and DB constraints in place, we have two types of errors to check. I’m not actually sure this change improves the legibility of the code. --- app/models/gestionnaire.rb | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/app/models/gestionnaire.rb b/app/models/gestionnaire.rb index 75461bd29..c18458dd7 100644 --- a/app/models/gestionnaire.rb +++ b/app/models/gestionnaire.rb @@ -27,21 +27,15 @@ class Gestionnaire < ApplicationRecord end def follow(dossier) - if follow?(dossier) - return - end - begin followed_dossiers << dossier + # If the user tries to follow a dossier she already follows, + # we just fail silently: it means the goal is already reached. rescue ActiveRecord::RecordNotUnique - # Altough we checked before the insertion that the gestionnaire wasn't - # already following this dossier, this was done at the Rails level: - # at the database level, the dossier was already followed, and a - # "invalid constraint" exception is raised. - # - # We can ignore this safely, as it means the goal is already reached: - # the gestionnaire follows the dossier. - return + # Database uniqueness constraint + rescue ActiveRecord::RecordInvalid => e + # ActiveRecord validation + raise unless e.record.errors.details.dig(:gestionnaire_id, 0, :error) == :taken end end