Sweet alert 2 in Ruby on Rails 7
Tags: rails, ruby, javascript, showdev
Published: 2023-02-01 06:28:14

## Sweet alert 2 in Ruby on Rails 7

Traditional alert boxes are looking so boring. We do not apply styling to them as well. There are a plethora of ways to change the styling of this. So in this article, we are going to talk about one of the best JS libraries, “Sweet Alert 2.”

![Sweet Alert with Rails 7 Created By [Rutik Patel](https://medium.com/@rutikkpatel)](https://cdn-images-1.medium.com/max/2560/1*o_a4aWV2Ta-oeBnegvkKXg.png)
<br>
## **Table of content**

 1. What is Sweet Alert 2?

 2. Integration of Sweet Alert with Ruby on Rails

 3. Sweet Alert 2 as an alert box

 4. Sweet Alert 2 with the destroy button

 5. AJAX call with Sweet Alert 2

 6. References

Let’s start with sweet alert,

---


### 1. What is Sweet Alert 2?

Sweet Alert is a JavaScript library that is used to make an alert box and toast messages more stylish, elegant, and appealing, and it is a piece of cake to design that.

![Sweet Alert 2 Logo by [https://sweetalert2.github.io/](https://sweetalert2.github.io/)](https://cdn-images-1.medium.com/max/2616/1*TD6R-_pxlRC6csRNzdsLSA.png)


### 2. Integration of Sweet Alert with Ruby on Rails

We are going to use **Rails 7.0.4** and **Ruby 3.1.0**.

Assume we have a simple crud rails application that was either scaffolded or manually created.

To use sweetalert, we are going to use Rails 7’s new importmap feature.
So let’s pin “Sweet Alert” using importmap.

    bin/importmap pin sweetalert2

Now we need to import this into the application.js. So, Add the following lines to the application.js

    import Swal from 'sweetalert2';
    window.Swal = Swal;

**Sweetalert has now been configured. Now you can use SweetAlert.**


### 3. Sweet Alert 2 as an alert box

We can modify the default alert box and add “Sweet Alert” instead of that.

    <button onclick= "defaultAlertBtn()"> Default Alert </button>
    <button onclick= "sweetAlertBtn()"> Sweet Alert </button>

Now add the script,

    <script>
      function defaultAlertBtn() {
        alert("Button has been clicked")
      }
      function sweetAlertBtn() {
        Swal.fire({
          icon: 'success',
          title: 'Button has been clicked',
        })
      }
    </script>

**Screenshots :**

![Default Alert Box](https://cdn-images-1.medium.com/max/3840/1*qScFmQoo2KYKRnS-TGXV5A.png)

![Sweet Alert Alert Box](https://cdn-images-1.medium.com/max/3840/1*0ibVtn0a9PZ_4soCyUCZ8g.png)


### 4. Sweet Alert 2 with the destroy button

We need to get confirmation from the user before deleting any data. So for that, we need to write some Javascript code.

Create the **delete_confirmation_dialog.js** file under the javascript folder. and Add the following code to it. app/javascript/delete_confirmation_dialog.js

    window.addEventListener(('turbo:load'), () => {
      document.addEventListener('submit', (event) => {
        if (event.target && event.target.className === 'delete-alertbox') {
          event.preventDefault()
          Swal.fire({
              title: 'Are you sure?',
              text: "You won't be able to revert this!",
              icon: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Yes, delete it!'
          })
            .then((result) => {
              if (result.isConfirmed) {
                document.querySelector('.delete-alertbox').submit()
              }
            })
            .catch(event.preventDefault())
        }
      })
    })

Then Include this file in **application.html.erb**. As a result, we can use that JavaScript code on any page of the application.

    <%= javascript_include_tag "delete_confirmation_dialog" %>

Finally, modify your destroy/delete button.

    <%= button_to "Delete", some_path, method: :delete, form_class: 'delete-alertbox'%>

**Screenshot:**

![Delete Confirmation Dialog using Sweet Alert](https://cdn-images-1.medium.com/max/3840/1*RC3TN5KQrzxyW8n4KFJLzQ.png)


### 5. AJAX call with Sweet Alert 2

You can also use this sweet alert in AJAX calls also.

    $.ajax({
      url: "/some_path",
      type: "post",
      data: { book_id: book.id },
      success: function (data) {
        Swal.fire({
          icon: 'success',
          title: 'AJAX call occurred successfully.',
          timer: 3000
        })
      },
      error: function (data) { },
    });

**Screenshot :**

![](https://cdn-images-1.medium.com/max/2000/1*4P8YU5HIqBA1rzQGUuAvBg.png)


### 6. References

My Github Repository : [https://github.com/rutikkpatel/Sweet-Alert-Rails](https://github.com/rutikkpatel/Sweet-Alert-Rails)

SweetAlert Github Repository : [https://github.com/sweetalert2/sweetalert2](https://github.com/sweetalert2/sweetalert2)

SweetAlert Website : [https://sweetalert2.github.io/](https://sweetalert2.github.io/)