Over a million developers have joined DZone.

Creating Modals in Rails

DZone's Guide to

Creating Modals in Rails

In this post, a developers gives a quick, step-by-step tutorial on how to create modals in your Rails application using JS and Ruby.

· Web Dev Zone ·
Free Resource

Learn how to add document editing and viewing to your web app on .Net (C#), Node.JS, Java, PHP, Ruby, etc.

Instead of writing a JavaScript application for working with remote modals in your Rails application, a much simpler approach is to render our views on a server and display them as modals. In this tutorial, we will explain how to implement this by using Bootstrap modals.

Step 1: Initial Setup

Add gem 'bootstrap' and gem 'popperjs' to your gemfile. Also, in your application.js file, include this 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.


<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">x</button>
  <h4 class="modal-title" id="myModalLabel">Modal title</h4>
<div class="modal-body">
  *Modal content comes here*
<div class="modal-footer">
  <button class="btn btn-primary">Save</button>

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


<%= link_to 'Add user', new_user_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window', class: 'btn btn-primary btn-lg'}  %>
<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content"></div>

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. <div> 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:


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

Step 3: Modify Your Controller

In the controller add the respond_to block to use AJAX:

def new
  respond_to do |format|

Step 4: Enjoy!

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


Thank you for staying with us until the end!

Extend your web service functionality with docx, xlsx and pptx editing. Check out ONLYOFFICE document editors for integration.

ruby on rails ,web dev ,javascript ,modals

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}