FIX: Constraint error when inserting the same topic group twice

If that happens, update the value instead of raising an error.
This commit is contained in:
Robin Ward 2019-12-12 13:10:46 -05:00
parent ff163ae980
commit 76f676879c
2 changed files with 16 additions and 4 deletions

View File

@ -41,14 +41,19 @@ class TopicGroup < ActiveRecord::Base
query = <<~SQL
INSERT INTO topic_groups (topic_id, group_id, last_read_post_number, created_at, updated_at)
SELECT tag.topic_id, tag.group_id, :post_number, :now, :now
FROM topic_allowed_groups tag
INNER JOIN group_users gu ON gu.group_id = tag.group_id
WHERE gu.user_id = :user_id
AND tag.topic_id = :topic_id
FROM topic_allowed_groups tag
INNER JOIN group_users gu ON gu.group_id = tag.group_id
WHERE gu.user_id = :user_id
AND tag.topic_id = :topic_id
SQL
query += 'AND NOT(tag.group_id IN (:already_updated_groups))' unless updated_group_ids.length.zero?
query += <<~CONFLICT
ON CONFLICT(topic_id, group_id)
DO UPDATE SET last_read_post_number = :post_number, created_at = :now, updated_at = :now
CONFLICT
DB.exec(
query,
user_id: user.id, topic_id: topic_id, post_number: post_number, now: DateTime.now, already_updated_groups: updated_group_ids

View File

@ -81,5 +81,12 @@ describe TopicGroup do
expect(created_topic_group.last_read_post_number).to eq new_post_number
expect(created_topic_group2.last_read_post_number).to eq topic2.highest_post_number
end
it "will not raise an error if a topic group already exists" do
TopicGroup.create_topic_group(user, @topic.id, 3, [])
expect(TopicGroup.find_by(group: group, topic: @topic).last_read_post_number).to eq(3)
TopicGroup.create_topic_group(user, @topic.id, 10, [])
expect(TopicGroup.find_by(group: group, topic: @topic).last_read_post_number).to eq(10)
end
end
end