How To Use Sweet Alert With Rails


I was tired of the boring looking confirm info box in my rails app. A quick Google search and I found Sweet Alerts.

I struggled to get this to work in my Ruby on Rails project for a couple reasons.

First, if you wanted to download the source files of Sweet Alerts and include them in your assets pipeline, go for it, but this post won’t cover that method.

I installed the sweet alert gem and the sweet alert confirm gem based on this user’s repo.

You will find a lot of tutorials on the internet using this repo to implement a sweet alert confirm message. I never got it to work and believe it is broken.

After more searching, I found that there is sweet alert 2.

Thanks to this StackOverflow question I found the first half of the solution.

How to get it all working

1. Install the gem with gem sweetalert2
2. Run bundle with $ bundle
3. Include this in your application.js file //= require sweetalert2 (I would put this at the top of the file and above your jQuery file .
4. Include this in your application.scss file *= require sweetalert2 (I would include this after the *= require_self statement).
5. You must override the allowAction method call because clicking yes on the dialogue box will not do anything. This can be achieved with the follow code. Either put it in your application.js file or another js file and call it into your application.js file.

Test it out

Now you can use the data method call and it will append the data-confirm attribute to your HTML and will call the new Sweet Alert box when clicked.

An example of implementation could be something like <%= link_to "Delete", note_path(note), method: :delete, data: { confirm: "Are you sure?" } %>

The result?

sweet-alert-confirm-box

You might also like...

From Beginner To Pro: 2 Week Facebook Marketing Course

I've spent over $20k in Facebook Ads. I will teach you everything I know about Facebook marketing. Sign up now for highly actionable and detailed lessons that are also 100% FREE! Drop your email below and lets get started.

Spam sucks, unsub whenever you'd like.