18. Bootstrap Modals

September 2015 · 2 minute read

Ensure all of the correct gems have been included into the app, the ones I’m using can be found in these locations:




1. Create a modal form to be rendered from the page you are on. In this, it’s going to be on the mybudget-show/home page because mybudget renders and controls the income partial.

<!-- Modal form -->
<div class="modal fade" id='new-income-modal-form' role='dialog'></div>
<!-- Modal form -->

2. Update the ‘new link’ in the partial view that will call the new modal

<!--<%= link_to 'Add Income', new_mybudget_income_path(@mybudget, @income) %>-->
<%= link_to new_mybudget_income_path(@mybudget, @income), remote: true, id: "new-item-link", class: "btn btn-sm btn-default round" do %> New

3. Create a new .js file under incomes which will be read by ‘Create’ in the incomes controller and direct to the appropriate partial view.

$("#new-income-modal-form").html("<%= j render('incomes/modal\_form\_new', income: @income) %>");

4. Create a new modal form partial which will be rendered in the modal form. It’s a good idea to make sure the new stuff works before destroying the old stuff.

<div class="modal-dialog reorder-modal-form">
  <div class="modal-content">
    <%= bootstrap_form_for([@mybudget, @income], remote: true) do |f| %></p> 
    <div class="modal-header">
      <h4 class="modal-title">
        New Income
    <div class="modal-body">
          <td class="field-name">
            <%= f.label :income %>
          <td class="field">
            <%= f.text_field :income %>
          <td class="field-name">
            <%= f.label :amount %>
          <td class="field">
            <%= f.number_field :amount %>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal" data-behaviour="form-clear">Cancel</button><br /> <%= f.submit class: "btn btn-primary", data: { trigger: 'loading' } %>
    <% end %>

5. Lastly, in the incomes controller update the respond_to format in the create action, ensuring that it formats the new .js file we have just created.

def create
  @income = @mybudget.incomes.build(income_params)

  respond_to do |format|
    if @income.save
      format.html { redirect_to [@mybudget, @incomes], notice: 'income was successfully created.' }
      format.json { render :show, status: :created, location: @income }
      format.js {redirect_via_turbolinks_to [@mybudget, @incomes]}

6. Always remember to test it out. Run the server and see if it works correctly. There is now a button link under incomes.

Everything works and redirects back to the mybudget home page. These 6 steps can now be replicated anywhere that I would like a modal view to appear.

See the working example at