Open a rails form with Twitter Bootstrap modals

This is a copy of my protip at Coderwall.com

Sometimes we require to open a form or display information that opens up as modal windows, I will show you an easy way to do it using twitter bootstrap modals.
First make sure you added the bootstrap-sass gem to your gemfile and also used bundle to install the gem.

Also in your application.js include the calling to the bootstrap-modal javascript file in the following way:

//= require bootstrap-modal

Now in the routes.rb file add the route to the partial you want to show as modal, for example:

get "project/new_release" => 'project#new_release', :as => :new_release

In the controller add the respond_to block to use some ajax magic

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

In the calling view use a link_to helper in the following way:

<%= link_to 'Add release', new_release_path,  {:remote => true, 'data_toggle' =>  "modal", 'data-target' => '#modal-window'}  %>

We need to have a DIV in the calling view that will load the partial as the modal window, so we are having something like this:

<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>

We are going to put the partial form inside that div with jquery.
Make sure to have the partial, in this case should be a file named _new_release.html.erb, inside this you will have the content you want to show for example:

 <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    **here comes whatever you want to show!**
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>

Now we need some javascript to make this works, make a file named same way as the controller action but with the suffix .js.erb for this example should be:

new_release.js.erb

And inside the file add the following:

$("#modal-window").html("<%= escape_javascript(render 'project/new_release') %>");

That’s it, now when you click on the link a nice modal will show up with a very clean fade effect. Hope this little snippet can be handy for you.

Autor: edokun

Mexican Passionate Software Developer and Agile Developer/Scrum Master, Free and Open Source Software enthusiast, Ruby and Rails trainee, occasional gamer, amateur photographer, a little of bass player, Ubuntu fan, Aikidoka an seeker of the true samurai spirit, loves Japan, and Mexican food.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *