You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5中Turbolinks与Bootstrap按钮下拉及布局异常问题

Hey there, let's work through this frustrating Turbolinks + Bootstrap problem you're facing. I've run into similar quirks before, so here's a step-by-step breakdown to get both your dropdowns working and layout back on track without ditching Turbolinks entirely:

1. Fix the Script Loading Order First

The order of your JS imports in application.js.coffee is critical here. When using Turbolinks with Bootstrap, you need to make sure jQuery and Bootstrap play nicely with Turbolinks's partial page reloads. Update your imports to follow this exact sequence:

#= require jquery
#= require jquery.turbolinks
#= require bootstrap-sprockets
#= require turbolinks
#= require_tree .

The jquery.turbolinks gem (make sure you've added it to your Gemfile and run bundle install!) acts as a bridge—it pauses jQuery event bindings during Turbolinks page loads and restores them afterward, which prevents Bootstrap's scripts from breaking when the page content gets swapped out.

Turbolinks doesn't do a full page refresh, so Bootstrap's JavaScript components (like dropdowns, tooltips, or modals) don't automatically re-bind to new content added after a page change. Fix this by adding a dedicated script to re-initialize them:

Create a new file app/assets/javascripts/turbolinks_bootstrap.js with this code:

$(document).on('turbolinks:load', function() {
  // Re-initialize dropdowns
  $('.dropdown-toggle').dropdown();
  
  // Add other Bootstrap components you use here too
  $('[data-toggle="tooltip"]').tooltip();
  $('[data-toggle="modal"]').modal();
});

This ensures every time Turbolinks finishes loading a new page segment, Bootstrap's components get hooked up correctly.

3. Verify Your Bootstrap Styles Setup

Layout issues often stem from incorrect style imports. If you're using Sass (which is standard in modern Rails), make sure your application.scss (rename it from .css if needed) has these imports in order:

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

Avoid importing both the standalone bootstrap CSS and bootstrap-sprockets—this can cause duplicate styles or layout conflicts that break your page.

4. Rule Out Script Conflicts

If the layout is still wonky after the above steps, it's worth checking for conflicting scripts. Temporarily comment out any custom JS or third-party libraries you've added, then re-enable them one by one. This will help you spot if another script is clashing with Turbolinks or Bootstrap's styles/scripts.

By following these steps, you should get your Bootstrap dropdowns working again, fix the layout chaos, and keep all the performance benefits of Turbolinks intact.

内容的提问来源于stack exchange,提问作者Muhammad Taha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:04:05