Use Sweet Alert 2 with a Destroy Button in Ruby on Rails 7
In Ruby on Rails Sep 15, 2022
Updated on May 13, 2023
In this post, we will discuss how we can integrate the Sweet Alert 2 library into a Rails 7 application. We will build a simple blog app and use SweetAlert2 for delete confirmation. We will use Rails 7.0.4 and Ruby 3.1.2.
Set Up a New Application
Let's get started by creating a new application. In the terminal, we type:
rails new my_blog
Then we change directories into this new project folder:
cd my_blog
Next, in the app/javascript/
folder, we'll create a sub-folder that we'll call js.
In the js folder, we will create a main.js file where we'll put our custom code.
Then in config/importmap.rb
, we add this:
pin_all_from "app/javascript/js", under: "js"
Now we can import main.js
in app/javascript/application.js
:
import "js/main"
Import Sweet Alert 2
We will use importmap
to import the Sweet Alert 2 library into our application. In the terminal, we type
the following command:
bin/importmap pin sweetalert2
Then in the main.js file we just created, we'll import it:
import Swal from "sweetalert2"
import * as sweetalert2 from "sweetalert2"
Generate a Scaffold for the Post Resource
Next, we will generate a scaffold for our Post
resource:
bin/rails g scaffold Post title:string content:string
Let's run the migration:
bin/rails db:migrate
Let's set the root
route of our application to the Post
index
action. In
config/routes.rb
, put this at the top:
root 'posts#index'
By default, Rails use the button_to
helper for the destroy
actions. This helper generates a
form with a button that submits to an URL. This form has a class attribute with a default value of
button_to
. Let's edit the Post
show
view to override this default. We want
something more specific. We will use the form_class
option to do that:
<%= button_to "Destroy this post", @post, method: :delete, form_class: 'delete-post' %>
Write the JavaScript Code
Finally, let's write the necessary JavaScript code to present a sweet alert box when users click this button. Let's open the main.js file we created and add the following code:
window.addEventListener(('turbo:load'), () => {
document.addEventListener('submit', (event) => {
if (event.target && event.target.className === 'delete-post') {
event.preventDefault()
Swal.fire({
title: "Are you sure?",
showCancelButton: true
})
.then((result) => {
if (result.isConfirmed) {
document.querySelector('.delete-post').submit()
}
})
.catch(event.preventDefault())
}
})
})
We cancel the event, then present the user with a sweet alert. The alert has a cancel button and a confirm button. If the user confirms they want to delete the post, we submit the form, and the post is deleted.
And that's all. From now on, when the user wants to delete a post, a fancy sweet alert popup will open, asking for confirmation.