LoginSignup
2
3

More than 5 years have passed since last update.

Ruby on RailsでHelloWorldプロジェクト

Last updated at Posted at 2018-11-21

はじめに

業務でruby on rails触ることになりました。
今回は基本的なWebアプリケーションを作成するまでの流れを学びます。
(プロジェクトの作成、モデル/ビュー/コントローラの作成、DBのデータ出力まで)

使用する環境

以下の環境で実施していきたいと思います。

> ruby -v
ruby 2.5.3p105 (2018-10-18 revision 65156) [x64-mingw32]
> bundle -v
Bundler version 1.17.1
> rails -v
Rails 5.2.1

image.png

あとMySQL(対応しているバージョンで!)


手順

bundleの準備

まずはプロジェクトフォルダを作ってinit。

> mkdir HelloWorld
> cd HelloWorld
> bundle init
> ./Gemfile

Gemfileを以下のように変更。
image.png

> bundle install --path vendor/bundle

上記の「--path vendor/bundle」のオプションを付けてインストールすることで、プロジェクトフォルダ(この場合のHelloWorld下)にgemを入れることができるようになる。
つまりプロジェクト単位で管理できる。

railsプロジェクトの作成

bundleの準備は出来たので、ここでrailsのプロジェクトを作成します。

// -B でBundle installをスキップできる
// -d で使用するDBを指定できる
// --skip-turbolinks でturbolinksをオフにする(今回はスキップ)
bundle exec rails new . -B -d mysql --skip-turbolinks

Overwrite C:/ruby_workspace/HelloWorld/Gemfile? (enter "h" for help) [Ynaqdhm]
と聞かれたのでYesで上書き

これでrailsプロジェクトの作成が完了しました。

動作確認(失敗)

実際に動くかどうかを確認します。

> bundle exec rails server
Could not find gem 'mysql2 (< 0.6.0, >= 0.4.4) x64-mingw32' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

oops…Gemfileを書き換えた後はbundle installですね。

bundle install --path vendor/bundle
bundle exec rails server

image.png

何もDB設定してませんでした。

DB設定

DB接続先設定

config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password ←ここだけ変更
  host: localhost

development:
  <<: *default
  database: HelloWorld_test_development

test:
  <<: *default
  database: HelloWorld_test_test

production:
  <<: *default
  database: HelloWorld_test_production
  username: HelloWorld_test
  password: <%= ENV['HELLOWORLD_TEST_DATABASE_PASSWORD'] %>

DB作成

> bundle exec rake db:create
Created database 'HelloWorld_development'
Created database 'HelloWorld_test'

動作確認(今度こそ)

> bundle exec rails server

image.png
無事に初期画面起動完了!

ということで、以下でMVCを使ったHelloWorldをしたいと思います。

MVCのモデル,テーブル作成

  • modelをコマンドから作成
> rails generate model hello_model
      invoke  active_record
      create    db/migrate/20181119015611_create_hello_models.rb
      create    app/models/hello_model.rb
      invoke    test_unit
      create      test/models/hello_model_test.rb
      create      test/fixtures/hello_models.yml
  • 作成したモデルを基にDBのテーブルを作成する

プロジェクト内の「db/migrate」の新たに作成されたファイルにDBのカラムを追加する。
t.[型] :[テーブル名]のように記載)

db/migrate/20181119015611_create_hello_models.rb
class CreateHelloModels < ActiveRecord::Migration[5.2]
  def change
    create_table :hello_models do |t|

      t.string :hello_text
      t.timestamps
    end
  end
end

以下のコマンドで作成を行う。

> bundle exec rake db:migrate
  • 作成したテーブルを確認
mysql> desc hello_models;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| hello_text | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

サンプルデータ作成

dbディレクトリ下の「seed.rb」を編集

db/seed.rb
HelloModel.create([{ hello_text: 'Hello' }, { hello_text: 'World'}])

以下のコマンドでサンプルデータの作成を行う

> bundle exec rake db:seed
  • 作成したデータを確認
mysql> select * from hello_models;
+----+------------+---------------------+---------------------+
| id | hello_text | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
|  1 | Hello      | 2018-11-19 02:56:55 | 2018-11-19 02:56:55 |
|  2 | World      | 2018-11-19 02:56:55 | 2018-11-19 02:56:55 |
+----+------------+---------------------+---------------------+
2 rows in set (0.00 sec)

MVCのビュー,コントローラの作成

bundle exec rails generate controller hello_controller hello_view
  • Viewを編集
hello_view.html.erb
<h1><%=@hello.hello_text %>!<%=@world.hello_text %>!!</h1>
<p>Find me in app/views/hello_controller/hello_view.html.erb</p>
<p>
    foreach check ->
    <% @hello_world.each do |text| %>
        <%= text.hello_text %>
    <% end %>
    !!
</p>

実行確認

> bundle exec rails server (起動している場合は不要)

image.png

できました!

補足

  • ビュー,コントローラの削除はこう
bundle exec rails destroy controller hello_controller hello_view
  • モデルの削除はこう
bundle exec rails destroy model hello_model
  • bundle install

対象範囲はGemfile内の新規gemをインストールする

  • 命名規則

モデルとかコントローラ名をhello_xxxって書いてましたが、
命名規則的にはHelloだけの方が良いみたいです。(キャメル)

参考

新規Railsプロジェクトの作成手順まとめ
https://qiita.com/yuitnnn/items/b45bba658d86eabdbb26

DBに慣れよう!Ruby on Railsのrakeコマンドでデータベースを作成する方法【初心者向け】
https://techacademy.jp/magazine/7207

MySQL5.7 から MySQL8.0にアップグレードしたらエラーが出る。
https://qiita.com/yoshi1729/items/8a023d28c92dc5e62f86

2
3
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
2
3