ゼロからWeb開発

ゼロからWeb開発

育休2回も経てる間に時代に取り残されちゃったWeb開発者のブログ

Railsアプリ作ってみました(indexページ作成編)

さてさてRuby on Railsに手を出していきましょう\(^o^)/

Ruby on Railsについての参照リンク

コマンドについて

ファイル構成について

indexの作成

まずはindexページを作ってみる。

今回はモデルなどは不要なので、コントローラーなど(コントローラ・ビュー・アセット・ルート・テスト・ヘルパー)を作成する。

$ cd /var/www/rails/branches
$ rbenv exec bundle exec rails g controller Welcomes index
           create app/controllers/welcomes_controller.rb
           route get 'welcomes/index'
           invoke erb
           create app/views/welcomes
           create app/views/welcomes/index.html.erb
           invoke test_unit
           create test/controllers/welcomes_controller_test.rb
           invoke helper
           create app/helpers/welcomes_helper.rb
           invoke test_unit
           invoke assets
           invoke coffee
           create app/assets/javascripts/welcomes.coffee
           invoke scss
           create app/assets/stylesheets/welcomes.scss

ルートの設定ファイルconfig/routes.rbを編集して、上記で作成したapp/views/welcomes/index.html.erbがindexページとして表示されるようにする。

$ vim config/routes.rb

内容

Rails.application.routes.draw do
   root :to => 'welcomes#index'    #これだけ追加
   get 'welcomes/index'
   # For details on the DSL available within this file, see  http://guides.rubyonrails.org/routing.html
end

確認

$ rbenv exec bundle exec rake routes
Prefix Verb URI Pattern Controller#Action
root GET / welcomes#index
welcomes_index GET /welcomes/index(.:format) welcomes#index

ブラウザでhttp://IPアドレスを見たとき、未だにpublic/index.htmlが表示されている…
http://IPアドレス:3000であれば

f:id:muzirushi78:20180415000437p:plain

エラーログの確認

$ vim log/production.log

ActionView::Template::Error (The asset "application.css" is not present in the asset pipeline.):

production環境では勝手にcssやjsをコンパイルしてくれないから、プリコンパイルしないといけないらしい。

$ rbenv exec bundle exec rake assets:precompile RAILS_ENV=production
Yarn executable was not detected in the system.
Download Yarn at https://yarnpkg.com/en/docs/install

Yarnを入れろと。

ちなみにYarnとはnpmに代わるNode.jsのライブラリやパッケージを管理するパッケージマネージャのことで

npmはNode.jsと一緒にインストールされるらしく、そういえばNode.js入れてなかったっけ?とnpm調べてみたら

$ npm -v
3.10.10

入ってたわ…いつの間に…無学…
npmに代わるYarnなので、npmでインストールも出来るけどbrewでのインストールが推奨されているらしい。
でも余計なのいれたくなry
とりあえずnpmでインストールしてみるYarn。

$ sudo npm install -g yarn

-gでグローバル領域にインストールされる。
~/.bash_profileにPATHを通しておく。

$ echo 'export PATH="$HOME/.yarn/bin:$PATH"' >> ~/.bash_profile
$ source ~/.bash_profile

確認

$ yarn -v
1.5.1

Rails起動後、ブラウザでhttp://IPアドレス:3000を確認

f:id:muzirushi78:20180415003950p:plain

表示された\(^o^)/

しかしNginx+Unicornを起動しているのだ…Rails起動はいらないのだ…
Nginxの設定ファイル見直し

$ sudo vim /etc/nginx/conf.d/branches.conf

内容

#root /var/www/rails/hogehoge/public;
root /var/www/rails/hogehoge;

再起動

$ sudo systemctl restart nginx

ブラウザでhttp://IPアドレスで確認

f:id:muzirushi78:20180415003950p:plain

表示された\(^o^)/
参考にしたサイトがpublic指定してたもんだから、それ指定しててもconfig/routes.rbが優先されるもんだと勝手に思っていたよ…ホンマ理解足りてない( ;∀;)

 

いつも長いので、今回はこのへんで。

その他の参考リンク

調査段階で、後々読みたいと思っているリンクたち

ヘルパーとかテストとかいらんやんと思ったら

ちょっと分かりづらかったアセットパイプラインやマイグレーションについて

セキュリティについて