Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Rails 5.1.0 and jQuery

I started using Rails v5.1.0 which I understand comes without jQuery as a default, however want to install jQuery to work with Zurb Foundation 6.

What's the best way to set this up as foundation is not currently loading modals?

like image 364
MrBiggs Avatar asked Apr 29 '17 14:04

MrBiggs


People also ask

Does rails come with jQuery?

Starting Rails 5.1, jQuery is not included by default. Let's add it on the Gemfile. To include the jQuery files in our application, we will require a few files on app/assets/javascripts/application. js .

What is Rails jQuery ujs?

jquery-ujs is a script, originally created for Ruby on Rails, to simplify common JavaScript actions and make it easier to execute RESTful actions through links. Even though it was created for Rails, it works perfectly with Laravel.


2 Answers

Summary:

  • Install Yarn
  • yarn add jquery
  • Add jquery to application.js manifest file

~~~

I came across this problem today as well.

In this article about using ActionCable with 5.1 I learned that the new way to get JQuery in your app is to use Yarn which is a javascript dependency manager (Think Gemfile and Bundler but for javascript).

You'll notice a new executable file when you create a new app in Rails 5.1: bin/yarn. Trying to run this without yarn installed on your system will lend the typical helpful "what to do next" message:

Download Yarn at https://yarnpkg.com/en/docs/install

  • If you are using homebrew on Mac, you can simply brew install yarn.

  • If you use Chocolatey on Windows, choco install yarn.

  • On Linux, the usual "add a repo and sudo apt-get install yarn apply. I'll let you wander over to the docs page to get the details.

Once you're yarned up, you can do:

yarn add jquery

which will add jquery to the .js dependency file: package.json. This is kind of like your application's "Javascript Gemfile", and Yarn is your "Bundler".

Now that you've got jquery added to your project, you can include it in your manifest the usual way.

//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap
//= require_tree .

You may also find this link helpful as well. It's an article talking about the new ideas for handling Javascript dependencies within Rails.

like image 124
Mr. Tim Avatar answered Nov 15 '22 23:11

Mr. Tim


Remove the default jQuery from the javascript manifest file by removing the line containing //= require jquery from app/assets/javascripts/application.js and then add your version of jquery. You can add your jQuery file in app/assets/javascripts and it will be picked up automatically or using a CDN version.

like image 44
Aref Aslani Avatar answered Nov 15 '22 22:11

Aref Aslani