diff --git a/backend/app/controllers/posts_controller.rb b/backend/app/controllers/posts_controller.rb index ba15e99..bf54551 100644 --- a/backend/app/controllers/posts_controller.rb +++ b/backend/app/controllers/posts_controller.rb @@ -314,7 +314,9 @@ class PostsController < ApplicationController def viewed return head :unauthorized unless current_user - current_user.viewed_posts << Post.find(params[:id]) + UserPostView.create_or_find_by!( + user: current_user, + post: Post.find(params[:id])) head :no_content end diff --git a/backend/spec/requests/posts_spec.rb b/backend/spec/requests/posts_spec.rb index aa5f7c1..ca74978 100644 --- a/backend/spec/requests/posts_spec.rb +++ b/backend/spec/requests/posts_spec.rb @@ -2559,6 +2559,21 @@ RSpec.describe 'Posts API', type: :request do expect(user.reload.viewed?(post_record)).to be(true) end + + it '204 and keeps one view on repeated requests' do + sign_in_as(user) + + expect { + post "/posts/#{ post_record.id }/viewed" + }.to change(UserPostView, :count).by(1) + expect(response).to have_http_status(:no_content) + + expect { + post "/posts/#{ post_record.id }/viewed" + }.not_to change(UserPostView, :count) + expect(response).to have_http_status(:no_content) + expect(user.reload.viewed?(post_record)).to be(true) + end end describe 'DELETE /posts/:id/viewed' do