Note: I am using bootstrap 4 modals here but this solution can be adapted to any JS modals implementations.

Check out working demo and source code.

Step 0. Prepare your bundle

Rails 4.2+

respond_with and the class-level respond_to methods have been extracted to the responders gem. To use them, simply add gem 'responders', '~> 2.0' to your Gemfile.

Other dependencies

You need to install bootstrap and jquery . Don’t forget to include them to asset pipeline.

gem 'bootstrap' gem 'jquery-rails'

Step 1. Modify your layout files

Also, we need to define a place where modals will be rendered. Let’s add it to application layout:

Step 2. Create modal.js

Now, we can move to the JavaScript part of our modals implementation. We want our links with data-modal attribute to be rendered in modal windows.

Also, we need to work on the remote forms submit. The application should properly handle redirects to the given page and form re-displays with errors. Let’s assume that if the response has Location header set, then we need to redirect the user to the given location, otherwise, we will re-display the form.

Step 3. Create Modal Responder

OK, now when we have prepared our front-end, we need to implement the server-side logic.

I am widely using respond_with in my applications, so I want something similar for modals.

The respond_with method is using the ActionController::Responder class for result rendering. Let’s make our own implementation and call it ModalResponder .

Here, we are overriding render and redirect_to methods to give them the new behavior when request is made via XHR.

If request is made via AJAX we want render to use our custom modal layout. And instead of redirecting we want redirect_to to return only headers with location header set which will handle our JS logic.

Step 4. Modify Application Controller

Now, when we have our custom, let’s add our own helper respond_modal_with . It will call the respond_with method with ModalResponder specified as the responder:

Step 5. Use it!

OK, now we have everything to use our cool remote modals. Let’s use them!

Well, in the first place, we need to add a link to the modal:

Now, we need to modify our controller using our new respond_modal_with method instead of respond_with :

And, finally, you should add two attributes to your form:

remote is used to tell jquery_ujs to submit this form with ajax. I am using request.xhr? because I want this form be fully functional both when displayed in modal and separately.

data-modal is used to tell our script to handle this form as the modal form.

I’ve created a small demo application which you can find here: source code on github.

UPD: Updated for Rails 5 And Bootstrap 4.