LoginSignup
0
0

More than 1 year has passed since last update.

Ruby on Rails 主要なDockerコマンド一覧

Last updated at Posted at 2022-02-03

前提

ruby 2.7.0
rails, ~> 6.0.3
mysql 5.7

rails new

MySQLを利用してrailsプロジェクトを作成する場合

docker-compose run --rm web rails new . --force --database=mysql
オプション 効果
--rm コンテナ終了時に自動的にコンテナを削除する
--force ファイルが存在する場合に上書きする
--no-deps 依存先のコンテナを起動させない
--database=postgresql PostgreSQLを利用する
--skip-bundle bundle installをスキップする
--api APIモードで作成する場合に使用(不要ファイルが作成されない)

gem更新時

docker-compose build web

コンテナにgemが存在するか確認する場合

docker compose run --rm web bundle info (gem名)

モデルの作成

docker-compose run --rm web bundle exec rails g model(モデル名)(カラム名)...

userモデルを作成 + カラムを2つ追加した場合

docker-compose run --rm web bundle exec rails g model user name:string email:string

カラムの追加

docker-compose run --rm web rails g migration Addカラム名Toテーブル名 カラム名:データ型

# Userテーブルに profile カラムを追加する場合
docker-compose run --rm web rails g migration AddProfileToUsers profile:text

カラムの削除

docker-compose run --rm web rails g migration Removeカラム名Fromテーブル名 カラム名:データ型

# Userテーブルに profile カラムを削除する場合
docker-compose run --rm web rails g migration RemoveProfileToUsers profile:text

中間テーブルの作成

docker-compose run --rm web bundle exec rails g model (モデル名)(モデル名①:references)(モデル名②:references)

courseuserの間を結ぶ中間テーブルを作成する場合

docker-compose run --rm web bundle exec rails g model course_user course:references user:references
db/migrate/xxxx_create_a_b.rb
class CreateCourseUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :course_users do |t|
      t.references :course, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end

コントローラの作成

docker-compose run --rm web rails g controller (コントローラ名) (アクション名)...

# api/v1/以下に ユーザーコントローラを作成する場合
docker-compose run --rm web rails g controller api/v1/users index create ...

マイグレーション

docker-compose run --rm web bundle exec rails db:migrate

ルーティングの確認

docker-compose run --rm  web bundle exec rails routes

Railsコンソール

サービス名・・・docker-compose.ymlで設定したservicesを指します。

docker compose run --rm (サービス名) rails c

もしくは

docker exec -it (イメージ名) /bin/bash

上記出力後、rails cを入力して実行する

root@xxxx:/xxxx# rails c

binding.pry

docker compose up -d && docker attach (コンテナ名)

seedデータ読み込み

docker-compose run --rm  web bundle exec rails db:seed

RSpecテスト

全てのテストを実行する

docker-compose run --rm  web bundle exec rspec
  • テストするファイルを指定する場合
  • 例題:「specディレクトリ→modelsディレクトリ→user_spec.rbファイル」
docker-compose run --rm  web bundle exec rspec spec/models/user_spec.rb
0
0
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
0
0