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

Rails集成Turbolinks时出现Uncaught TypeError: $(...).barrating is not a function错误的技术求助

I’ve run into this exact type of compatibility issue between Turbolinks and jQuery plugins before. The root problem here is how Turbolinks handles page navigation and caching: when you leave a page, Turbolinks caches its state instead of doing a full refresh. When you return, it restores that cached page—but the jQuery plugin methods (like barrating) can get lost in the process, even though the plugin script is still in the <head>.

Here are the most reliable fixes to get your rating bars working across Turbolinks navigations:

1. Double-Check Your Script Load Order

First, make sure your plugin loads before your custom rating code in application.js. If your custom code runs before the plugin is registered, it’ll fail on subsequent page loads:

// application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require barrating.min  // Load the plugin first
//= require ratings        // Then load your custom logic
//= require_tree .

Native document.addEventListener can sometimes be finicky with Turbolinks’ lifecycle. Switch to jQuery’s event binding for turbolinks:load, and add a safety check to destroy existing instances before reinitializing:

// assets/javascripts/ratings.js
$(document).on('turbolinks:load', function() {
  console.log('page is fully loaded');
  
  // Only attempt to destroy if the barrating method exists
  if ($.fn.barrating) {
    $('#user_track_rating_drums').barrating('destroy');
  }

  // Initialize the rating bar
  $('#user_track_rating_drums').barrating({
    theme: 'bars-horizontal',
    reverse: true,
    initialRating: 1,
    onSelect: function(value, text, event) {
      if (typeof(event) !== 'undefined') {
        const ratingClassEl = document.getElementById('average_drums_class');
        if (value >= 8) {
          ratingClassEl.className = 'green';
        } else if (value >= 6) {
          ratingClassEl.className = 'yellow';
        } else if (value >= 3) {
          ratingClassEl.className = 'orange';
        } else {
          ratingClassEl.className = 'red';
        }
        console.log(event.target);
      }
    }
  });
});

3. Clean Up Instances Before Page Caching

Turbolinks caches pages before navigation, so leftover plugin instances can cause conflicts when the page is restored. Use the turbolinks:before-cache event to destroy all rating bar instances before the page is cached:

// Add this to ratings.js
$(document).on('turbolinks:before-cache', function() {
  if ($.fn.barrating) {
    $('.barrating').barrating('destroy');
  }
});

4. Fallback: Reload the Plugin If Needed (Last Resort)

If the above fixes don’t work, you can add a safety check to reload the plugin script if the barrating method is missing. This isn’t ideal for performance, but it’s a reliable fallback:

// ratings.js
function initRatingBar() {
  $('#user_track_rating_drums').barrating({
    // Your existing configuration here
    theme: 'bars-horizontal',
    reverse: true,
    initialRating: 1,
    onSelect: function(value, text, event) {
      // Your onSelect logic here
      if (typeof(event) !== 'undefined') {
        const ratingClassEl = document.getElementById('average_drums_class');
        if (value >= 8) {
          ratingClassEl.className = 'green';
        } else if (value >= 6) {
          ratingClassEl.className = 'yellow';
        } else if (value >= 3) {
          ratingClassEl.className = 'orange';
        } else {
          ratingClassEl.className = 'red';
        }
        console.log(event.target);
      }
    }
  });
}

$(document).on('turbolinks:load', function() {
  if (typeof $.fn.barrating === 'undefined') {
    // Reload the plugin script then initialize
    $.getScript('/assets/barrating.min.js', initRatingBar);
  } else {
    initRatingBar();
  }
});

These fixes work because they align your plugin initialization with Turbolinks’ page lifecycle—ensuring the plugin methods are available when you need them, and cleaning up instances to avoid conflicts with cached pages.

内容的提问来源于stack exchange,提问作者Bryan Spence

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:12:50