From 1cffe09c2b698a6755d8cc00083d3462fc0c95c6 Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Tue, 5 Jan 2021 18:16:02 +0800 Subject: [PATCH] Update Photo upload url for add user login as photo path --- app/controllers/photos_controller.rb | 2 +- app/models/photo.rb | 1 + app/uploaders/photo_uploader.rb | 2 +- test/controllers/photos_controller_test.rb | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/controllers/photos_controller.rb b/app/controllers/photos_controller.rb index 8214d1b649..512957afda 100644 --- a/app/controllers/photos_controller.rb +++ b/app/controllers/photos_controller.rb @@ -10,7 +10,7 @@ def create end # 浮动窗口上传 - @photo = Photo.new(image: params[:file], user_id: current_user.id) + @photo = Photo.new(image: params[:file], user: current_user) if @photo.save render json: { ok: true, url: @photo.image.url(:large) } else diff --git a/app/models/photo.rb b/app/models/photo.rb index 2daf8bd069..a1074cbb49 100644 --- a/app/models/photo.rb +++ b/app/models/photo.rb @@ -5,4 +5,5 @@ class Photo < ApplicationRecord # 封面图 mount_uploader :image, PhotoUploader + after_commit :remove_image!, on: :destroy end diff --git a/app/uploaders/photo_uploader.rb b/app/uploaders/photo_uploader.rb index 1c35f485a9..18f7411958 100644 --- a/app/uploaders/photo_uploader.rb +++ b/app/uploaders/photo_uploader.rb @@ -5,7 +5,7 @@ class PhotoUploader < BaseUploader def filename if super.present? @name ||= SecureRandom.uuid - "#{Time.now.year}/#{@name}.#{file.extension.downcase}" + "#{model.user&.login || Time.now.year}/#{@name}.#{file.extension.downcase}" end end end diff --git a/test/controllers/photos_controller_test.rb b/test/controllers/photos_controller_test.rb index 86326245d3..e2fcd0d029 100644 --- a/test/controllers/photos_controller_test.rb +++ b/test/controllers/photos_controller_test.rb @@ -11,7 +11,7 @@ post photos_path, params: { file: file } assert_equal 200, response.status assert_equal true, response.parsed_body["ok"] - assert_match Regexp.new("/uploads/photo/#{Date.today.year}/[a-zA-Z0-9\\-]+.png!large"), response.parsed_body["url"] + assert_match Regexp.new("/uploads/photo/#{user.login}/[a-zA-Z0-9\\-]+.png!large"), response.parsed_body["url"] end it "POST /photos failure for blank data" do