3 steps on how to build a modal with Ruby on Rails

3 steps on how to build a modal with Ruby on Rails

After finish Ruby on Rails projects at Microverse, I had to work on the final Ruby on Rails project. It was a budget transaction web app ๐Ÿ‘€(repo), once I got the requirements I checked the required design, and I thought that it would be great to add a modal dialog, so I did.


1. Add gems

  • Add gem bootstrap and gem popperjs to Gemfile. Then install

    bundle install
  • Go to application.js file and add, don't forget should be in this order

    //= require jquery
    //= require popper
    //= require turbolinks
    //= require bootstrap
    //= require_tree.

    The require statement is used to call all bootstrap dependency in that order

2. Change view layouts

  • Create a partial view _new.html.erb file add the content you want to use it. This is going to be modal view
# _new.html.erb

<div class="modal-header">
  <h5 class="modal-title">Feed the piglet </h5>
  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&times;</span>
<div class="modal-body">
      `All modal content in here`
  • And in the index.html.erb add the modal
# fab button
<div class="btn-group-fab" role="group" aria-label="FAB Menu">
    <%= link_to '<button type="button" class="btn btn-main btn-secondary has-tooltip" data-placement="left" title="Menu"> <i class="fa fa-plus"></i> </button>'.html_safe, new_festival_path,  {remote: :true, 'data-toggle': 'modal', 'data-target': '#modal-window'} %>
# modal element
<div id="modal-window" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content"></div>
  • Create a new file javascript erb file new.js.erb
# new.js.erb

$("#modal-window").find(".modal-content").html("<%= j (render 'new') %>");

With JQuery this file links the modal element with the new Rails route

3. Modify the controller

In the controller in the new method, add the respond_to block to use AJAX

# festivals_controller.rb 

  def new
    @festival = Festival.new
    respond_to do |format|

And voila, now we have this festival-music.gif


A modal will help us to avoid reloading to the next page and to return again to the same one. In the end, this is more intuitive for the final user. We keep in the same, complete the transaction and stay on the same page, keeping away from the backing and forth on pages.

I'm sure there are plenty of ways in order on how to do it, however, this is an easy way to achieve also is much more detailed information.

Leave a comment if you found this post helpful or liked it. Also, let me know if you have another approach to deal with the same issue

Follow me @btandayamo on Twitter

Taken from: dzone.com/articles/rails-creating-modals