[Ruby on Rails] Delete s3 images with Active Strage

Target

Delete images on s3 as well as local

Premise

About image deletion with Active Strage I'm stuck, so I'll leave it as a memorandum. (Please note that this is a fumbling description, so it may be wasteful.)

Also, delete unnecessary images on s3.

post model Column name: string Action new index show edit update create destroy Root resouses: posts

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina heroku

Introducing image posting with Active Strage

[Rails 5.2] How to use Active Storage This was very easy to understand and easy to introduce, so Please introduce it referring to here.

[Rails] How to make images posted on Heroku (ActiveStorage + Amazon S3) Please also refer to this when deploying to heroku.

About image deletion with Active Strage

This is the main subject. The Rails Guide describes how to delete it, and uses the purge method. By using this purge method, you can delete s3 images directly from the rails app.

python


#Synchronously destroy the avatar and the actual resource file.
user.avatar.purge

#Asynchronously destroys the associated model and the actual resource file via Active Job.
user.avatar.purge_later

About deleting one image

In the case where you have to delete the image of s3 (1) When updating the image (2) It is possible that the post associated with the image has been deleted. Also, the reason has not been clarified yet, but if you use purge instead of purge_later, Because the destroy action was not destroyed and the if statement became false. Using purge_later worked fine. Asynchronous destruction may be required with purge_later for deleting one image.

The order of @ post.image.purge_later && @ post.destroy If you do @ post.destroy first, @ post.image.purge_later will I think that it will affect the server trouble of aws, so I am doing it in this order.

app/controllers/posts_controller.rb


  def update
    @post = Post.find(params[:id])
    if @post.image.attached?
      @post.image.purge_later
    end
    if @post.update(post_params)
      redirect_to post_path(@post)
    else
      render :edit
    end
  end

  def destroy
    @post = Post.find(params[:id])
    if @post.image.attached?
      if @post.image.purge_later && @post.destroy
        redirect_to posts_path
      else
        render :edit
      end
    else
      if @post.destroy
        redirect_to posts_path
      else
        render :edit
      end
    end
  end

  private
  def post_params
    params.require(:post).permit(:name, :image)
  end

About deleting multiple images

Posting / deleting multiple images with Active Storage I tried to implement it referring to this article, In my development environment

ActiveSupport::MessageVerifier::InvalidSignature


 Because I could not solve it due to the error
 I decided to delete all the images.
 Therefore, we have added a new img_destroy action.

 Also, if you use purge_later to delete multiple images as opposed to deleting one image,
 Occasionally an error (I don't remember the details, but there is too much processing?)
 It may come out, but using purge worked fine.

 The order of @ post.image.purge && @ post.destroy
 If you do @ post.destroy first, @ post.image.purge will
 I think that it will affect the server trouble of aws, so I am doing it in this order.


#### **`python`**
```rb

  def update
    @post = Post.find(params[:id])
    if @post.update(post_params)
      redirect_to post_path(@post)
    else
      render :edit
    end
  end

  def destroy
    @post = Post.find(params[:id])
    if @post.images.attached?
      if @post.images.purge && @post.destroy
        redirect_to posts_path
      else
        render :edit
      end
    else
      if @post.destroy
        redirect_to posts_path
      else
        render :edit
      end
    end
  end

  def img_destroy
    @post = Post.find(params[:id])
    if @post.images.purge
      redirect_to edit_post_path(@post)
    else
      render :edit
    end
  end

  private
  def post_params
    params.require(:post).permit(:name,images: [])
  end

config/routes.rb


delete 'post_image_delete/:id', to: 'posts#img_destroy', as: 'post_img_destroy'

erb:app/views/posts/edit.html.erb


<% if @post.images.attached? %>
  <%= link_to "Delete all", post_img_destroy_path(@post), method: :delete, "data-confirm" => "Are you sure you want to delete it?", class: "btn btn-danger" %>
<% end %>

Summary

It was a method to delete the image of s3 together with Active Strage, There may be a better way to write it for groping.

I myself moved to Active Storage because I couldn't resolve the gem refile-s3 error. I hope I can help people in the same situation. For more information here

Also, on twitter, technologies and ideas that have not been uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork

Recommended Posts

[Ruby on Rails] Delete s3 images with Active Strage
[Ruby on Rails] Upload multiple images with refile
[Ruby on Rails] View test with RSpec
Notes on using FCM with Ruby on Rails
[Ruby on Rails] Controller test with RSpec
Ruby on Rails controller create / delete command
[Ruby on Rails] About Active Record callbacks
[Ruby on Rails] Model test with RSpec
Post / delete multiple images with Active Storage
Introducing Rspec with Ruby on Rails x Docker
Publish the app made with ruby on rails
[Rails] Procedure for linking databases with Ruby On Rails
Determine the current page with Ruby on Rails
[Ruby on Rails] Post editing function (update, delete)
I made a portfolio with Ruby On Rails
[Rails 6] RuntimeError with $ rails s
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
Run Ruby on Rails RSpec tests with GitHub Actions
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Created RSS / Atom format sitemap with Ruby on Rails
Ruby on rails learning record -2020.10.03
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Ruby on Rails basic learning ①
Test Active Strage with RSpec
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
Commentary on partial! --Ruby on Rails
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
Ruby on rails learning record -2020.10.06
Ruby on Rails validation summary
Ruby on Rails Basic Memorandum
I tried installing Ruby on Rails related plugin with vim-plug
[Ruby on Rails] Add a column with a foreign key constraint
[Rails] Create API to download files with Active Storage [S3]
Delete all the contents of the list page [Ruby on Rails]
[Ruby on Rails] Implement login function by add_token_to_users with API
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
Install Ruby on MSYS2 with pacman
Ruby on Rails Overview (Beginner Summary)
[Ruby on Rails] Read try (: [],: key)
[Ruby on Rails] yarn install --check-files
Ruby on Rails variable, constant summary
[Ruby on Rails] Introduced paging function
I want to add a browsing function with ruby on rails
Ruby on Rails development environment construction with Docker + VSCode (Remote Container)
Basic knowledge of Ruby on Rails
Move Active Storage on S3 locally
Progate Ruby on Rails5 Looking Back
How to use Ruby on Rails
Understand code coverage with Rspec, the Ruby on Rails test framework
[Ruby on Rails] Add / Remove Columns
Programming with ruby (on the way)
Ruby on Rails Japanese-English support i18n
(Ruby on Rails6) "Erase" posted content