1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails6(Ruby on Rails6) にBootstrapをWebpackerを使って導入する方法

Last updated at Posted at 2021-06-07

Rails6(Ruby on Rails6) にBootstrapをWebpackerを使って導入する方法

2021年、すでにRails6が到来したにも関わらず、まだ出版される書籍にはRails4を前提にアプリ開発方法を教えている。その結果、自分のPC環境(Rails6)では書籍の説明通りにはいかず、エラーが時々発生していて、その中の一つ、Bootstrapと取り入れる方法に挫折を味わったが、複数回の試しにより得た解決方法をここにまとめておく。

環境の整理

  • 開発環境:Windows10 Home 64ビットオペレーティングシステム、x64ベースプロセッサ
  • Rails version 6系(Rails 6.1.3.2)

環境の構築

  1. フォルダを作成(今回例:test_bootstrap)

  2. フォルダをルートディレクトリに指定、そのあとbundle init

  3. Gemfileを編集(gem "rails"のコメントアウトを外す)

  4. bundle config set path vendor/bundle

  5. bundle install

  6. bundle exec rails new . -d postgresql -f

  7. config/database.ymlを以下のように設定する(postgresql)
    スクリーンショット 2021-06-07 101452.png
    *設定しないと、ActiveRecord::ConnectionNotEstablished エラとなる
    スクリーンショット 2021-06-07 102440.png

  8. rails db:create

  9. rails s

  10. 以下までは完了
    スクリーンショット 2021-06-07 102833.png

動作確認用のファイルを用意

  1. rails g controller home index
    確認用のページ(コントローラ:home, アクションメソッド:index)を作成
    スクリーンショット 2021-06-07 103148.png

  2. ブラウザでルートにアクセスした際に、home#indexを表示するよう、config/routes.rbを編集
    スクリーンショット 2021-06-07 103431.png

  3. app\views\home\index.html.erb にBootstrapのclassを指定する
    スクリーンショット 2021-06-07 100902.png

  4. rails s ブラウザで確認(現在:黒色の文字列、期待値:赤色の文字列)
    スクリーンショット 2021-06-07 100846.png

Bootstrapの導入

  1. WebpakerでjQueryとpopper.jsというパッケージをインストール
    yarn add jquery popper.js bootstrap

  2. config\webpack\environment.js を以下のように変更
    スクリーンショット 2021-06-07 103919.png

  3. app\javascript\packs\application.js にて、以下1行を追加

app\javascript\packs\application.js
import 'bootstrap'

*追加後
スクリーンショット 2021-06-07 104207.png

  1. app\assets\stylesheets\application.css をapp\assets\stylesheets\application.scss にファイル拡張子を変更
  2. app\assets\stylesheets\application.scss にて、以下1行を追加
app\assets\stylesheets\application.scss
 *= require bootstrap/dist/css/bootstrap.min.css

*追加後
スクリーンショット 2021-06-07 104432.png
6. rails s ブラウザで確認(期待値:赤色の文字列 となった。OK)
スクリーンショット 2021-06-07 101204.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?