6

I am installing jQuery in my 5.1.x Rails app via the jquery-rails gem.

In the gem setup, they recommend to add these lines to application.js by default:

//= require jquery
//= require jquery_ujs

But, in a Rails 5.1.x app, you have already this line which doesn't depend on jQuery anymore:

//= require rails-ujs

I suppose both are doing the exact same thing and one is not needed.

Should I keep both anyway or should I prefer only jquery_ujs or only rails-ujs?

Hartator
  • 5,029
  • 4
  • 43
  • 73

2 Answers2

3

As of Rails 5.1 jQuery is no longer required for UJS (unobtrusive javascript). So if you have no need of jQuery in your rails app, you can just use

//= require rails-ujs

On the other hand, if you do use jQuery in your app, and use the jquery-rails gem, and you should NOT require rails-ujs, but should instead use:

//= require jquery
//= require jquery_ujs

Requiring jquery_ujs along with jQuery can cause issues in the app, and you may see the following JS console error:

Uncaught Error: jquery-ujs has already been loaded!

agbodike
  • 1,796
  • 18
  • 27
2

jquery-ujs is a thing of the past as of Rails 5.1, you don't need it.

Kit
  • 113
  • 2
  • 10
  • 2
    Except if you're still using jQuery. `rails-ujs` doesn't support jQuery - it was crafted exactly to get rid of jQuery dependency. – Aurel Branzeanu Jan 04 '18 at 21:38
  • This is true as long as you aren't migrating an old code base that uses the old patterns. The `rails-ujs` library is not a drop-in replacement if you've been using `jquery-ujs`, especially (mostly?) around ajax requests and the arguments w/ event data changing. It does not seem to be well documented as best I could find and I had some issues where the responses didn't seem to be consistently returned in args as expected. I had to turf the upgrade for now. As a note, https://dev.to/nejremeslnici/migrating-from-jquery-ujs-to-rails-ujs-k9m was helpful to get me 95% of the way. – rylanb Aug 10 '22 at 19:50