0
1

Ruby On RailsにおけるjQuery初期設定

Last updated at Posted at 2024-04-15

Ruby On RailsにおけるjQuery初期設定

背景説明

現在のrailsに即したjQuery導入説明です。
私のような初学者にも伝わる日本語での説明を見つけられませんでした。英語での説明はあったのでこちらにメモしておきます。
ムダな記述が多いです。記述を省ける箇所や訂正箇所をコメントで教えてください。1

初期設定

アプリを作成します。

rails new useJquery

作成したフォルダーへ移動

cd useJquery

コントローラーとビューを作成

rails g controller tests index

ルーティング設定

Rails.application.routes.draw do
  get 'tests/index'
  root to: "tests#index"
end

app/views/tests/index.html.erbへの書き込み

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

jQuery導入

ここからが本題

Gemfileへの追加

##中略
gem "jquery-rails"
gem "bootstrap"
gem "sassc-rails"

ダウンロード

bundle install

app/assets/stylesheets/application.cssの拡張子をscssへ変更

mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss

app/assets/stylesheets/application.scssへ以下を追加

*= @import "bootstrap";

config/initializers/assets.rbへ以下を追加

Rails.application.config.assets.precompile += %w( jquery.min.js jquery_ujs.js bootstrap.min.js popper.js )

config/importmap.rbへ以下を追加

pin "jquery", to: "jquery.min.js", preload: true
pin "jquery_ujs", to: "jquery_ujs.js", preload: true
pin "popper", to: "popper.js", preload: true
pin "bootstrap", to: "bootstrap.min.js", preload: true

app/javascript/application.jsへ追加2

//必ず、これらを先頭に記す
import "jquery"
import "jquery_ujs"
import "popper"
import "bootstrap"
//以下他のファイル

javascript実行

javascriptファイル作成

touch app/javascript/change_color.js

config/importmap.rbへ追加

pin "change_color", to: "change_color.js"

app/javascript/application.jsへ追加

import "change_color"

app/javascript/change_color.jsにスクリプトを記載3

$("#hoge").css("color","red");

このように赤色になっているなら成功です。

Image from Gyazo

  1. 参考文献

  2. importされる順番が大事です。必ず、controllersなどより上に記してください

  3. 参考文献

0
1
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
0
1