はじめに
駆け出しのエンジニアがRailsで新規アプリケーションを作成しviewを表示させるまでのメモ。
hamlを使用しています。
Version
Programming歴: 70日目
Ruby: 2.3.1
Rails: 5.0.1
Step 1 - アプリケーションの作成
$ cd
一旦ホームディレクトリに戻って、
$ cd projects
アプリケーションを作成・保存したいディレクトリに移動する。今回は「projects」ディレクトリにアプリケーションを作成・保存します。
$ rails new <新規アプリケーションの名前> -d mysql
「-d」はデータベースの種類を指定するオプション。今回はmysqlを用いてアプリケーションを作成します。
create
create README.md
create Rakefile
create config.ru
...
...
...
Use `bundle show [gemname]` to see where a bundled gem is installed.
run bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted
ズダダダーっとterminalが走って、rails newコマンドが完了。projectsディレクトリ以下に新規アプリケーションが作成されました。
$ cd <新規アプリケーションの名前>
アプリケーションのディレクトリに移動しましょう。
$ rake db:create
データベースを作成し、
$ rails s
「rails s」コマンドでサーバーを立ち上げて、「http://localhost:3000/」 にアクセス。以下のような画像が表示されればOK!

2. Model、Controller、Viewの作成と最低限のRouting
今後、「rails g」コマンドを用いてModelやControllerなどを作成していくが、
その際一緒にデフォルトで生成されてしまうhelper file、test file、assetsを生成されないように
以下のように記述を加える。(この3つは、必要になった時に手動で作れば良い、と思う。)
config.generators do |g|
g.helper false
g.test_framework false
g.assets false
end
●Model作成
$ rails g model <modelの名前(単数形)>
今回はまずevent modelを作りたいので、
$ rails g model event
とします。
●table作成
$ rake db:migrate
●Controller作成
$ rails g controller <Controllerの名前(複数形)>
今回はまずevent controllerを作りたいので、
$ rails g controller events
とします。
●View作成
今回viewはhamlで記述したいので、gemをインストールします。Gemfileに以下を追記し、
gem 'haml-rails'
gem 'erb2haml'
$ bundle install
これでhamlが使えるようになりました。
デフォルトでアプリ内にあるerbファイルをhamlに変換したいので、以下のコマンドを実行。
$ rails haml:replace_erbs
アプリ内のerbファイルをhamlに置き換えました。
その上で、app/views/eventsに、index.html.hamlを手動で作成。中に適当に文字を書きます。
Create an app from scratch!!
●Routingの設定
Rails.application.routes.draw do
root "events#index"
resources :events, only: [:index]
end
このように記述。
これで、完了!
http://localhost:3000/
にアクセスすると以下のような表示になるはず。

ならない場合はサーバー立ち上げ忘れの可能性あり。「rails s」を再度する。