LoginSignup
7
10

More than 3 years have passed since last update.

【jQuery】RailsでjQueryを使う

Last updated at Posted at 2020-04-09

学習中に作っていたrailsアプリでjQueryを使いたかったのですが、
設定方法があいまいだったのでざっと調べました。
参考にしていただけると幸いです。

jQueryを使いたい。

作業内容

1.  'jquery-rails'の導入
2.  turbolinksの停止。
3.  読み込みの確認。

1.  'jquery-rails'を導入する

最下行にjquery-railsを記載します。

Gemfile
gem 'jquery-rails'

2.  turbolinksを停止させる

Gemfileからturbolinksをコメントアウトする。

Gemfile
 ~変更前~
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5' 

 ~変更後~
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
# gem 'turbolinks', '~> 5' # この行をコメントアウトする

( turbolinksはRails 4以降デフォルトでGemfileに導入されています。)

!ここでGemfileを変更したので、bundle installをします。


次に、application.html.haml から turbolinks の部分を削除します。
(application.html.erbから、hamlに変換しています。)

application.html.haml
 ~変更前~
!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title giga-app
    = csrf_meta_tags
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'  このオプションを消す
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'  このオプションを消す
  %body
    = render "layouts/notifications"
    = yield

 ~変更後~
 省略
    = stylesheet_link_tag    'application', media: 'all'
    = javascript_include_tag 'application'
 省略

最後にapplication.js から turbolinks の部分を削除します。

application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery      
//= require jquery_ujs
//= require turbolinks  ⬅️ ここを削除する
//= require_tree .


3.  Jsファイルの読み込みを確認。

実際の処理を記述するjsファイル( 今回は item.jsとします )に、
以下の記述をし、ブラウザで読み込みを確認します。

item.js

$(function(){
});

ここで、コンソールに何もエラーが出なければ問題なく読み込めています。

うまく読み込めていないと、何かしらエラーが出ています。
Image from Gyazo


ここまで問題なく進むと、RailsにてjQuery を使う準備が完了です。

ご覧いただきありがとうございました。

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10