Rails creating modals

2018-02-06 09:42:17来源:oschina作者:Kolosek人点击


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

Addgem 'bootstrap' andgem '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.


Modal title

*Modal content comes here*

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'}%>

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 withclass = "modal hide fade" you can add an extra fade effect to the modal, too! ajax, while

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

$("#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|
endStep 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:


Thank you for staying with us until the end!

Originally published at kolosek.com .