Just rely on the constraints to avoid duplicate Follows
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.
This commit is contained in:
parent
ba48a1da6e
commit
d417907f36
1 changed files with 6 additions and 12 deletions
|
@ -27,21 +27,15 @@ class Gestionnaire < ApplicationRecord
|
||||||
end
|
end
|
||||||
|
|
||||||
def follow(dossier)
|
def follow(dossier)
|
||||||
if follow?(dossier)
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
begin
|
begin
|
||||||
followed_dossiers << dossier
|
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
|
rescue ActiveRecord::RecordNotUnique
|
||||||
# Altough we checked before the insertion that the gestionnaire wasn't
|
# Database uniqueness constraint
|
||||||
# already following this dossier, this was done at the Rails level:
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
# at the database level, the dossier was already followed, and a
|
# ActiveRecord validation
|
||||||
# "invalid constraint" exception is raised.
|
raise unless e.record.errors.details.dig(:gestionnaire_id, 0, :error) == :taken
|
||||||
#
|
|
||||||
# We can ignore this safely, as it means the goal is already reached:
|
|
||||||
# the gestionnaire follows the dossier.
|
|
||||||
return
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue