Using Toastr In Rails
A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions.
The code snippet below shows an action that takes place in the controller. Whenever a user is deleted a flash notice of “deleted successfully” is shown on the screen.
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_back fallback_location: '/', notice:"Deleted Successfully"
end
Here is the code you add to the view template where you want the flash message to display.
<p class="flash"><%= notice %></p>
How to Install Toastr in Rails 6.0
yarn add toastr
Now navigate to `app/javascript/packs/application.js` and add the line of code below, you can add it just above `require(“@rails/ujs”).start()`
@import "toastr/toastr";
Now let’s see if it works, navigate to `app/views/layouts/application.html.erb`, and add the line of code below just before the end body tag.
...
<%= yield %>
<script>
toastr.success('Welcome to rails!!')
</script>
</body>
Fire up your application with `rails server`, you should have something like this.
Just before you go, remember our first code snippet? Let’s replace the `notice` with our new setup toastr.
<% if flash.any? %>
<script type="text/javascript"><% flash.each do |key, value| %>
<% type = key.to_s.gsub('alert', 'error').gsub('notice', 'success') %>
toastr.<%= type %>('<%= value %>')
<% end %>
</script>
<% end %>
To get a full grasp of how toastr works see the documentation.
I hope you find this article useful, if it is, share your comments below.