close

Instead of writing a JavaScript application for working remote modals in your Rails application, it is a much more simple approach 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 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.

_new.html.erb

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

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

index.html.erb

<%= 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>
  </div>
</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:

new.js.erb

$("#modal-window").find(".modal-content").html("<%= j (render 'new') %>");
$("#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 your end work result:

bootstrap-modal

Thank you for staying with us until the end!

Originally posted on kolosek.com.

文章標籤
ruby on rails
全站熱搜
創作者介紹
創作者 Kolosek 的頭像
Kolosek

Kolosek

Kolosek 發表在 痞客邦 留言(0) 人氣()