RailsでHello World
Rails、いろんなファイルが勝手に作られて意味不〜という話を書きました。
今日はこのパートⅡということで、scaffoldを使わずにHello worldとだけ表示するアプリケーションを作る。 (上の記事より先にこっち書くべきだったな...)
①アプリケーションの生成(rails new)
書式:$ rails new アプリケーション名 [オプション]
$ rails new messageを実行し、完了したら$ cd messageで生成されたmessageディレクトリに移動する。
たくさんのファイルが生成されていることがわかる↓
% ls -1FA .browserslistrc .git/ .gitignore .ruby-version Gemfile Gemfile.lock README.md Rakefile app/ babel.config.js bin/ config/ config.ru db/ lib/ log/ node_modules/ package.json postcss.config.js public/ storage/ test/ tmp/ vendor/ yarn.lock
②コントローラーの生成(rails g controller)
書式:$ rails g controller コントローラー名 [アクション名 [...]]
gはgenerateの略。
コントローラー名は通常、小文字の英字複数形。対してモデル名は単数形。
% rails g controller greetings index
Running via Spring preloader in process 6123
create app/controllers/greetings_controller.rb
route get 'greetings/index'
invoke erb
create app/views/greetings
create app/views/greetings/index.html.erb
invoke test_unit
create test/controllers/greetings_controller_test.rb
invoke helper
create app/helpers/greetings_helper.rb
invoke test_unit
invoke assets
invoke scss
create app/assets/stylesheets/greetings.scss
app/controllersディレクトリの中にgreetings_controller.rbという名前でGreetingsControllerクラスのファイルが生成される。
# app/controllers/greetings_controller.rb class GreetingsController < ApplicationController def index end end
index.html.erb
また、indexという名前のアクション(コントローラーのインスタンスメソッド)がGreetingsControllerクラスの中に設定され、そのアクションによって呼ばれるビューテンプレートファイルであるindex.html.erbもapp/views/greetingsの中に生成される↓
# app/views/greetings/index.html.erb <h1>Greetings#index</h1> <p>Find me in app/views/greetings/index.html.erb</p>
config/routes.rb
それに伴い、HTTPリクエストの宛先(URI)とGreetingsコントローラーのアクションを結びつけるルートがconfig/routes.rbファイルの中に追加される。
# config/routes.rb Rails.application.routes.draw do get 'greetings/index' end
ルーターにはGreetingsコントローラーのindexアクションを呼び出すためのルートが記述されている。
greetings/indexは宛先URIを示しているが、さらにURIとコントローラーのアクションとの紐付けの指示も含んでいる。
get 'greetings/index'
これは、以下のように記述されるところが省略されている。
get 'greetings/index', 'greetings#index'
③ビューのカスタマイズ
app/views/greetings/index.html.erbを編集してHello worldと表示する画面を作る。
# app/views/greetings/index.html.erb <h1>messageアプリ</h1> <p>Hello world</p>
④サーバを起動して確認(rails s)
messageのアプリケーションフォルダにいる状態でRailsサーバの起動コマンドであるrails sを実行する。sはserverの略。
http://localhost:3000/greetings/indexにアクセスすると、Hello worldと表示される。

次はscaffoldを使って簡単なアプリケーションを作るよ!!