LoginSignup
167
160

More than 5 years have passed since last update.

RailsでjQueryを使えるようにする方法

Last updated at Posted at 2018-05-06

環境

Rails 5.2.0

やり方

①Gemの追加

Gemfileにgem "jquery-rails"を記述する。

bundle updateを実行。

②application.jsに追記

//= require jquery
//= require jquery_ujs
の二つを/app/assets/javascripts/application.jsに追記しましょう。

application.js
//= require activestorage
//= require turbolinks
//= require_tree .
//= require jquery #追加
//= require jquery_ujs #追加

③レイアウトファイルの確認

app/views/layouts/application.html.erbを開き、
javascrip_include_tage の次にapplicationを指定しておきましょう。


<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

これを実行することでスクリプトファイルを読み込むためのスクリプトタグを自動的に生成してくれます。

試しに使ってみる

適当にコントローラとビューを作り、jQueryが動作しているのか確かめて見ましょう。

test.html.erb
<h1>Ajax#index</h1>
<p id="hoge">赤色になるよ</p>

Cards.png

ではjQueryを使って文字を赤色に表示してみましょう。

test.html.erb

<h1>Ajax#index</h1>
<p id="hoge">赤色になるよ</p>

<script>
  $("#hoge").css("color","red")
</script>

ここではhogeを指定して色を変えているので以下のような表示になっているかと思います。
Cards.png

色が変わっていればjQueryが正常に動作しています。

もしjQueryが使えていなかったら。

念のため、以下を確認しておきましょう。
rails sを再起動したか
bundle updateしたか

それでも適応されない!って場合は、@kumagi さんの記事も参考にしてみましょう。
https://qiita.com/kumagi/items/289ccadf344f32613304

167
160
2

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
167
160