Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Creating Rails Modals Using Bootstrap

Instead of writing your own JavaScript code for handling remote modals in your Rails application, it is a much simpler approach to implement it by using Bootstrap. In this tutorial, we will explain how to do it efficiently.

Step 1: Initial setup

Add gem 'bootstrap' and gem 'popperjs' to your Gemfile and run bundle install.
After installing the gems, update your application.js in the following order:

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

Step 2: Modify layouts in View

Make sure that this view is partial. Inside it, you will have the content you want to show in the modal.

_new.html.erb




We need to define a place where modals will be rendered:

index.html.erb

 true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window', class: 'btn btn-primary btn-lg'}  %>

Remote is used to tell jquery to submit this form with ajax, while 'data-toggle' => "modal" is used to tell our script to handle this form as the modal form. loads the partial as a modal window and with class="modal hide fade" you can add an extra fade effect to the modal, too!

To make this all work we need to add some JavaScript:

new.js.erb

$("#modal-window").find(".modal-content").html("");
$("#modal-window").modal();

Step 3: Modify your Controller

In the controller add the respond_to block to be able to use Ajax:

def new
  respond_to do |format|
    format.html
    format.js
  end
end

Step 4: Enjoy!

We have finally reached the end! Now you just need to click on "Add user" button and a nice modal will show up with a fade effect! This is our final result:

Thank you for staying with us until the end.

If you want to read more about Rails, be sure to subscribe to our newsletter!



This post first appeared on 13 Remote Development Myths, please read the originial post: here

Share the post

Creating Rails Modals Using Bootstrap

×

Subscribe to 13 Remote Development Myths

Get updates delivered right to your inbox!

Thank you for your subscription

×