Skip to content

Commit

Permalink
CV2-5419: rescue ActiveRecord::RecordNotUnique for relationship save (#…
Browse files Browse the repository at this point in the history
…2071)

* CV2-5419: rescue ActiveRecord::RecordNotUnique for relationship save

* CV2-5419: delete suggested relation before create confirmed one
  • Loading branch information
melsawy authored Oct 9, 2024
1 parent 5d80f05 commit b6c59c6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
29 changes: 19 additions & 10 deletions app/models/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -155,18 +155,27 @@ def create_or_update_parent_id

def self.create_unless_exists(source_id, target_id, relationship_type, options = {})
r = Relationship.where(source_id: source_id, target_id: target_id).last
if r.nil?
r = Relationship.new
r.skip_check_ability = true
r.relationship_type = relationship_type
r.source_id = source_id
r.target_id = target_id
options.each do |key, value|
r.send("#{key}=", value) if r.respond_to?("#{key}=")
ret = r
if !r.nil? && relationship_type == Relationship.confirmed_type && r.relationship_type != relationship_type
r.destroy
ret = nil
end
if ret.nil?
begin
r = Relationship.new
r.skip_check_ability = true
r.relationship_type = relationship_type
r.source_id = source_id
r.target_id = target_id
options.each do |key, value|
r.send("#{key}=", value) if r.respond_to?("#{key}=")
end
ret = r.save ? r : nil
rescue ActiveRecord::RecordNotUnique
ret = Relationship.where(source_id: source_id, target_id: target_id).last
end
r.save ? r : nil
end
r
ret
end

protected
Expand Down
17 changes: 17 additions & 0 deletions test/models/relationship_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -255,5 +255,22 @@ def setup
r2 = Relationship.create_unless_exists(source.id, target.id, Relationship.confirmed_type)
end
assert_equal r, r2
# Should update type if the new one is confirmed
target = create_project_media team: t
r = create_relationship source_id: source.id, target_id: target.id, relationship_type: Relationship.suggested_type
r2 = nil
assert_no_difference 'Relationship.count' do
r2 = Relationship.create_unless_exists(source.id, target.id, Relationship.confirmed_type)
end
assert_nil Relationship.where(id: r.id).last
assert_equal Relationship.confirmed_type, r2.relationship_type
Relationship.any_instance.stubs(:save).raises(ActiveRecord::RecordNotUnique)
target = create_project_media team: t
r = nil
assert_no_difference 'Relationship.count' do
r = Relationship.create_unless_exists(source.id, target.id, Relationship.confirmed_type)
end
assert_nil r
Relationship.any_instance.unstub(:save)
end
end

0 comments on commit b6c59c6

Please sign in to comment.