11
10

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 1 year has passed since last update.

Rails7をちょっと試す(Bootstrap編)

Last updated at Posted at 2022-01-17

はじめに

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 のリンクをボタンっぽくしてみます。

app/views/users/index.html.erb
<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"} %>

ブラウザの画面は以下のようになります。
bootstrap1.png

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 になります。

参考情報

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?