はじめに
Rails 7.0.0 では、Bootstrap が簡単に利用できるようになっています。
今回は、Bootstrap を試してみたいと思います。
Bootstrap を使うためには、npm と yarn が必要です。
以下のバージョンで確認しました。
- Ruby 3.0.2
- Rails 7.0.0
- npm 8.3.0
- yarn 1.22.17
Rails プロジェクトを作る
新しくRailsプロジェクトを作ります。このとき --css
を指定します。
(データベースオプションを指定しているのに深い意味はありません。)
mkdir rails_sandbox
cd rails_sandbox
rails new . --database=postgresql --css=bootstrap
scaffold を実行する
scaffold を使って簡単なCRUDを作ります。 Bootstrap
の確認をしたいだけなので適当です。
bin/rails g scaffold User name
DBを作成し migration を実行する
bin/rails db:create db:migrate
Rails を実行する
動作を確認するため、Rails を実行します。 Procfile.dev
を指定して foreman
bin/dev
を実行します。
bin/dev
ブラウザからアクセスする
http://localhost:3000/users
にアクセスします。
Bootstrap が使えることを確認する
Bootstrap
が使えることを確認するため、 app/views/users/index.html.erb
を修正します。
New User
のリンクをボタンっぽくしてみます。
<p style="color: green"><%= notice %></p>
<h1>Users</h1>
<div id="users">
<% @users.each do |user| %>
<%= render user %>
<p>
<%= link_to "Show this user", user %>
</p>
<% end %>
</div>
<%= link_to "New user", new_user_path, {class: "btn btn-primary mx-1"} %>
Bootstrap のバージョン
package.json
を調べてみたところ、Bootstrap のバージョンは 5.1.3 になってました。
$ grep bootstrap package.json
"bootstrap": "^5.1.3",
"build:css": "sass ./app/assets/stylesheets/application.bootstrap.scss ./app/assets/builds/application.css --no-source-map --load-path=node_modules"
まとめ
今回は、Bootstrap が使えることを確認しました。
試したコードは、 https://github.com/suketa/rails_sandbox/tree/try_rails7_bootstrap になります。