0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【コア機能】Rails導入、MySQL導入

Last updated at Posted at 2025-11-05

ここまでのおさらい
1、html,cssでざっくりとUIを作成。
2、メイン機能の動きをJavaScriptで記述することができました。

今後の流れ
htmlに直書きしてJavaScriptで表示させている値をMySQLにDBを作成。
Railsで処理を書く。
RailsのActiveRecord機能を使用してDBを引っ張ってくる。

目次

[0]Ruby on Rails導入
[1]Node.js
[2]mySQL導入確認
[3]RailsにmySQL導入
[4]DB作成
[5]モデル作成、データ構造(テーブル定義)確認

[0]Ruby on Rails導入

  • 0-1 ブランチを新しく切る(念の為)
    ex) feature/rails-new
    これでRails導入前にも戻れる様に保険をかけれました。
  • 0-2 オリジナルプロダクトのルートディレクトリで
    rails newを実行。
    README.mdなど、既に作成済みのファイルは上書きするかどうか聞かれるので、その都度回答をすればRailsの導入は完了です。

[1]Node.js

私はフレームワークにRubyonRailsを使用するため、
DBをJsonに変換してJavaScriptに読み込ませるためのNode.js等は導入しません。

1 import maps
import mapsは、バージョン付けされたファイルに対応する論理名を用いてJavaScriptモジュールをブラウザで直接importできます。import mapsはRails 7からデフォルトになっており、トランスパイルやバンドルの必要なしにほとんどのnpmパッケージを用いて誰でもモダンなJavaScriptアプリケーションを構築できるようになります。
import mapsを利用するアプリケーションは、Node.jsやYarnなしで機能します。RailsのJavaScript依存関係をimportmap-railsで管理する予定であれば、Node.jsやYarnをインストールする必要はありません。
import mapsを利用する場合、別途ビルドプロセスを実行する必要はなく、bin/rails serverコマンドでサーバーを起動するだけでOKです。
参考;Railsガイド8.0v

[2]mySQL導入

  • 2-1まずは導入済みか確認
    mysql --version
    以下のようにバージョンの返答があれば導入済み。
    返答がなければmysql導入から始める必要があります。
mysql  Ver 9.3.0 for macos15.2 on arm64 (Homebrew)
  • 2-2導入済みであれば起動済みか確認
    brew services list
    下記のようにstartedと返答があればOK
Name  Status  User          File
mysql started megumikishibe ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

stoppedと返答があればbrew services start mysqlで起動が必要。

  • 2-3起動済みである確認が取れたら接続確認
    mysql -u root又はmysql -u root -p(パスワード付きの場合)を実行し、下記のように返答があればOK
Welcome to the MySQL monitor.  Commands end with ; or \g.
.
.
.
mysql> 

この返答が確認できればexitで抜けてOKです。

[3]RailsにmySQL導入(初期設定からmySQLに変更)

  • 3-1
    Railsの初期設定ではSQLiteが設定されている。
    私はmySQLしか触った事がない為、既視感のあるmySQLに設定を変更します。

まず Gemfile に mysql2 があるか確認
grep mysql2 Gemfileを実行し、返答がなければまだmysqlは繋がっていません。
規定はSqLiteのため、返答がないはずです。

  • 3-2返答がない事を確認後、
    bundle add mysql2を実行しmySQLを繋げます。

  • 3-3config/database.ymlを編集
    mySQL用のymlに書き換える

Rails公式テンプレート

# MySQL. Versions 5.7 and up are supported.
#
# Install the MySQL driver:
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem "mysql2"
#
# And be sure to use new-style password hashing:
#   ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
#

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  host: localhost

development:
  <<: *default
  database: appname_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: appname_test

production:
  <<: *default
  database: appname_production
  username: <%= ENV["APPNAME_DATABASE_USERNAME"] %>
  password: <%= ENV["APPNAME_DATABASE_PASSWORD"] %>

公式テンプレをlogi-balance用に書き換え

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  host: localhost

development:
  <<: *default
  database: logi_balance_development

test:
  <<: *default
  database: logi_balance_test

production:
  <<: *default
  database: logi_balance_production
  username: <%= ENV["LOGI_BALANCE_DATABASE_USERNAME"] %>
  password: <%= ENV["LOGI_BALANCE_DATABASE_PASSWORD"] %>

Rails公式GitHub


これでRailsへのmySQL接続の設定は完了です。
私はRailsを作ってからmySQLを接続したため、
ymlファイルを書き換える手間が発生してしまいました。
以下のブログの通り、rails newをするときに、一緒に接続させる方法を取ると、自動で書き換えてくれるようです。
参考blog

[4]DB作成

プロダクトのルートディレクトリで以下を実行。

rails db:create

Railsがconfig/database.ymlの内容を確認し、それに沿ったDBの基礎を作ってくれます。
以下のように返答がありました!

Created database 'logi_balance_development' 
Created database 'logi_balance_test'

[5]モデル作成、データ構造(テーブル定義)作成

今回使用するテーブル定義書は以下です。
テーブル定義

依存の浅いテーブルから順に rails g model を実行。
今回は以下の順番で作成することにしました。

①	Employees	Deliveries が参照するため
②	Courses	Deliveries・Driver_Assignments が参照
③	Deliveries	外部キー先がすべて存在する状態で作成
④	Destinations	Delivery_Stops で使用
⑤	Delivery_Stops	Deliveries・Destinations が必要
⑥	Driver_Assignments	Employees・Courses が必要
⑦	Score_Snapshots	Deliveries が必要

全部のコードを載せると膨大すぎるため、
①Employeesだけを参考に載せます。

  • 5-1 Employeesテーブル作成(model)
rails g model Employee employee_no:integer name:string hired_on:date
  • 5-2 作成されたdb/migrate
class CreateEmployees < ActiveRecord::Migration[8.0]
  def change
    create_table :employees do |t|
      t.integer :employee_no
      t.string :name
      t.date :hired_on

      t.timestamps
    end
  end
end

私のオリジナルプロダクト「Logi-Balance]に関して、
要件定義書や画面遷移図等を以下のGitHub上で公開しております。
GitHub

注意
私はプログラミング学習歴1年未満の初学者です。
この記事は自身の備忘録用として掲載しております。
間違いがあるかと思いますので、今後の学習のためにコメントにご指摘を頂けますと幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?