開発環境
windows wsl(Debian GNU/Linux 9)
DB構築(Ubuntu)
sudo apt install mysql-server mysql-client -y sudo apt install default-libmysqlclient-dev -y sudo mysql_secure_installation
sudoつけないと権限エラーになる問題を解決する方法
drop user 'root'@'localhost'; create user 'root'@'%' identified by 'root'; grant all privileges on *.* to 'root'@'%' with grant option; flush privileges;
プロジェクト構築
プロジェクト作成
rails new todoapp -d mysql
初回のみbundleのインストールは--pathオプションを付ける
次回以降は.bundleが作成されるため--pathオプションは不要である。
bundle install --path vendor/bundle
以下のエラーが出たので
An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.
エラーログに従う。
gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/
HTMLテンプレートエンジンをEBRからSLIMへ変更
Genfileに以下を追記する。
gem 'slim-rails' gem 'html2slim'
gemを更新したのでbandleを更新する。
bundle install
ERBをslimへ変換後、ERBを削除。
bundle exec erb2slim app/views/layouts/ --delete
SCSSを用いる設定に変更
(cssフレームワークを使う必要ない方は無視してください)
.\app\assets\stylesheets\配下の
application.cssを削除しapplication.scssを作成。
DBを作成
bin/rails db:create
サーバ起動動作確認
bin/rail s
model作成
bin/rails g model [モデル名] [属性名:データ型 ...]
bin/rails g model Task name:String description:text
モデルの自動生成での成果物表
| 成果物 | パス | 説明 |
|---|---|---|
| モデルクラス | app/models/task.rb | タスククラス |
| マイグレーションファイル | db/migration/現在日時_create_tasks.rb | DBへの変更を行う |
| 自動テスト | test/models/task_test.rb | 自動テストを行う |
| 自動テストを行うfixture | test/fixture/task.yml | 自動テストに使用するテストデータの投入定義 |
controller/view作成
bin/rails g controller コントローラー名 [アクション名 ...][オプション]
bin/rails g controller task index show new edit
アクション一覧
index、show、new、edit、create、update、destroy
すべてのアクションに対してルーティングを行うことができる記述。
taskに関するルーティング記述を削除し、以下を記述する。
記載場所:config/routes.rb
resources :task
ルートパス(http://localhost:3000)にアクセスしたした時のルーティング設定
記載場所:config/routes.rb
root to: 'task#index'
サーバ起動動作してindexが表示されれば成功。
bin/rail s
追記
ルーティングのパスがバージョンによって違う?
エラーが出るときは以下で確認して設定する。
/bin/rails routes