discourse/app/models/post_reply_key.rb
Blake Erickson 35e17ce115
FIX: Email Send post has already been taken error (#16992)
* FIX: Email Send post has already been taken error

Adding a failing test first before coming up with a good solution.

Related: 357011eb3b

The above commit changed

```
PostReplyKey.find_or_create_by_safe!
```

to

```
PostReplyKey.create_or_find_by!
```

But I don't think it is working as a 1-1 replacement because of the
`Validation failed: Post has already been taken` error we are receiving
with this change. Also we need to make sure we don't re-introduce any
concurrency issues.

Reported: https://meta.discourse.org/t/224706/13

* Remove rails unique constraint and rely on db index

I believe this is what is causing `create_or_find_by!` to fail. Because
we have a unique constraint in the db I think we can remove this rails
unique constraint?

* clean up spec wording
2022-06-06 13:13:26 -06:00

38 lines
885 B
Ruby

# frozen_string_literal: true
class PostReplyKey < ActiveRecord::Base
belongs_to :post
belongs_to :user
before_validation { self.reply_key ||= self.class.generate_reply_key }
validates :post_id, presence: true
validates :user_id, presence: true
validates :reply_key, presence: true
def reply_key
super&.delete('-')
end
def self.generate_reply_key
SecureRandom.hex(16)
end
end
# == Schema Information
#
# Table name: post_reply_keys
#
# id :bigint not null, primary key
# user_id :integer not null
# post_id :integer not null
# reply_key :uuid not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_post_reply_keys_on_reply_key (reply_key) UNIQUE
# index_post_reply_keys_on_user_id_and_post_id (user_id,post_id) UNIQUE
#