Bootstrap modal in ruby on rails not working

2020-03-30 04:49发布

问题:

I'm trying to implement a modal to create a new user for my app. For some reason a can't make it work.

This code just fade in and out, and no modal is showing up, i can't figure out why. In fact, I'm using the exact same code from this answer How to add bootstrap modal with link_to so the link content open in modal ?

<%= link_to "Open modal", "#myModal", :class => "btn", "data-toggle" => "modal" %>
      <!-- Modal -->
      <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <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">
          <p>One fine body…</p>
        </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>
      </div>

My gems:

gem 'rails',        '5.0.2'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.18', '< 0.5'
gem 'faker',          '1.6.6'
gem 'will_paginate',           '3.1.0'
gem 'bootstrap-will_paginate', '0.0.10'
gem 'bcrypt',         '3.1.11'
gem 'bootstrap-sass', '3.3.6'
gem 'puma',         '3.4.0'
gem 'sass-rails',   '5.0.6'
gem 'uglifier',     '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks',   '5.0.1'
gem 'jbuilder',     '2.4.1'

below line in app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-sprockets

And my scss

@import "bootstrap-sprockets";
@import "bootstrap";

回答1:

You need to remove the hide class from the #myModal modal, because that's given it a display: none !important CSS rule, that's why you can't see it:

Check with this:

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <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">
        <p>One fine body…</p>
      </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>
    </div>
  </div>
</div>

And most probably you'll need to wrap your .modal-header within a <div class="modal-dialog" role="document"> and a <div class="modal-content"> to see your it "well".



回答2:

The modal will disappear immediately after showing. So I delete //= require bootstrap-sprockets in the application.js file and solve this problem. FYI