comments: add uniqueness constraint on votes.

This commit is contained in:
evazion
2021-01-23 14:44:11 -06:00
parent 5061b0a013
commit b689c9cbed
3 changed files with 26 additions and 3 deletions

View File

@@ -0,0 +1,5 @@
class AddUniqueUserIdIndexToCommentVotes < ActiveRecord::Migration[6.1]
def change
add_index :comment_votes, [:user_id, :comment_id], unique: true
end
end

View File

@@ -5008,10 +5008,11 @@ CREATE INDEX index_comment_votes_on_user_id ON public.comment_votes USING btree
--
-- Name: index_comments_on_created_at; Type: INDEX; Schema: public; Owner: -
-- Name: index_comment_votes_on_user_id_and_comment_id; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX index_comments_on_created_at ON public.comments USING btree (created_at);
CREATE UNIQUE INDEX index_comment_votes_on_user_id_and_comment_id ON public.comment_votes USING btree (user_id, comment_id);
--
-- Name: index_comments_on_body_index; Type: INDEX; Schema: public; Owner: -
@@ -5020,6 +5021,13 @@ CREATE INDEX index_comments_on_created_at ON public.comments USING btree (create
CREATE INDEX index_comments_on_body_index ON public.comments USING gin (body_index);
--
-- Name: index_comments_on_created_at; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX index_comments_on_created_at ON public.comments USING btree (created_at);
--
-- Name: index_comments_on_creator_id_and_post_id; Type: INDEX; Schema: public; Owner: -
--
@@ -7883,6 +7891,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20210108030724'),
('20210110015410'),
('20210110090656'),
('20210115015308');
('20210115015308'),
('20210123112752');

View File

@@ -14,6 +14,15 @@ class CommentVoteTest < ActiveSupport::TestCase
should validate_inclusion_of(:score).in_array([-1, 1]).with_message("must be 1 or -1")
end
should "not allow creating duplicate votes" do
v1 = create(:comment_vote, comment: @comment, user: @user)
v2 = build(:comment_vote, comment: @comment, user: @user)
assert_raise(ActiveRecord::RecordNotUnique) do
v2.save(validate: false)
end
end
context "creating" do
context "an upvote" do
should "increment the comment's score" do