仮想開発環境の構築トップページ


Ruby on Rails で Web システムを開発する

仮想開発環境が構築できたので,Ruby on Rails による Web システムの開発を行ってみよう.

Ruby on Rails のインストール

仮想マシンにログインした後,ruby と sqlite3 がインストールされていることを確認し,gem コマンドを使って rails をインストールする.

[vagrant@localhost ~]$ ruby -v ⏎ # ruby のバージョンを確認
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]
[vagrant@localhost ~]$ sqlite3 --version ⏎ # sqlite3(データベース管理システム)のバージョンを確認
3.33.0 2020-08-14 13:23:32 fca8dc8b578f215a969cd899336378966156154710873e68b3d9ac5881b0alt2
[vagrant@localhost ~]$ gem install rails ⏎ # rails をインストール
(中略)
Successfully installed rails-6.1.3
(中略)
Done installing documentation for rack, concurrent-ruby, sprockets, zeitwerk, tzinfo, i18n, activesupport, nokogiri, crass, loofah, rails-html-sanitizer, rails-dom-testing, rack-test, erubi, builder, actionview, actionpack, sprockets-rails, thor, method_source, railties, mimemagic, marcel, activemodel, activerecord, globalid, activejob, activestorage, actiontext, mini_mime, mail, actionmailer, actionmailbox, websocket-extensions, websocket-driver, nio4r, actioncable, rails after 77 seconds
38 gems installed
[vagrant@localhost ~]$

プロジェクトの作成

プロジェクト用のフォルダを作成する.今回は 「~/Documents/」に「rails」フォルダを作成し,その中に「myapp」というプロジェクトを生成する.

[vagrant@localhost ~]$ pwd ⏎ # 
/home/vagrant
[vagrant@localhost ~]$ ls ⏎ # 
centos7ansible  Documents
[vagrant@localhost ~]$ cd Documents/ ⏎ # 
[vagrant@localhost Documents]$ ls ⏎ # 
laravel
[vagrant@localhost Documents]$ mkdir rails ⏎ # 
[vagrant@localhost Documents]$ ls ⏎ # 
laravel  rails
[vagrant@localhost Documents]$ cd rails/ ⏎ # 
[vagrant@localhost rails]$ ls ⏎ # 
[vagrant@localhost rails]$

rails new コマンドで myapp という名前(何でもよい)のプロジェクトを作成する.

[vagrant@localhost rails]$ rails new myapp ⏎
      create
      create  README.md
      create  Rakefile
      create  .ruby-version
(中略)
Using rails 6.1.3
(中略)
Webpacker successfully installed 🎉 🍰
[vagrant@localhost rails]$

生成された myapp ディレクトリに移動し,rails プロジェクトが正しく生成されていることを確認するために,web サーバを立ち上げて接続してみる.なお,ここでは,IP アドレスが 192.168.33.110 になっていますが,ここで設定した IP アドレスを指定してください.

[vagrant@localhost rails]$ ls ⏎
myapp
[vagrant@localhost rails]$ cd myapp/ ⏎
[vagrant@localhost myapp]$ rails server -b 192.168.33.110 ⏎
=> Booting Puma
=> Rails 6.1.3 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.2.2 (ruby 3.0.0-p0) ("Fettisdagsbulle")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 19187
* Listening on http://192.168.33.110:3000
Use Ctrl-C to stop

ブラウザから接続するときには http://192.168.33.110:3000/ のように ,ポート番号に 3000 番を指定する.次のような画面が表示されればOKです.

r-01

Web サーバを終了するには Ctrl + C を押す.