By default, Rails give us some plain flash notification. I’m gonna show you how to get from this:
To this:
Pretty cool uh?.
Lets begin
1.Creating the project
The first thing we need is to create the project, I’m gonna upload this code to Heroku so I need
my database to be Postgresql, the flag -M is to not have mailers files and -T is because we don’t need tests for this app:
2.Generating all the MVC part
To keep this simple we are gonna create the model Person with a name and an age, all this is gonna be
created with the magic of scaffold:
Then, create the database and do the migrations:
Finally, and before running the app, change the routes:
Now lets create the first person of the list to see the rails default notification:
Time to do some magic.
3.Adding Toastr to our project
Go to Toastr and download the .zip file or .tar.gz depending of your OS. Once that you have It, open It and copy toastr.min.js and toastr.js.map into app/assets/javascript. Now, if you don’t want to modify the style of the notifications copy toastr.min.css intoapp/assets/stylesheets otherwise use the toastr.css and custom the toasts as you wish.
Time to define our alerts
4.Creating custom flash types
With this you can define all the alerts you want:
Add that line in your application_controller
Now, go to app/views/layouts/application.html.erb and before the tag <%= yield %> add
<%= render :partial => 'flash_messages', :flash => flash %> like this:
Lets add that partial.
Create a file with the name _flash_messages.html.erb in a new folder called app/views/application/
and add the following code
Each flash here is one of the flash that we created before.
5.Modifying the controller
Finally, go to app/controllers/people_controller.rb and update your alerts for the ones that we created like this: