6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rails consoleでmigrationをする

Last updated at Posted at 2018-11-22

新しくmodelを作って色々やりたいときに、
rails g model hogeをして
rails db:migrateをして
rails cでデータ操作をして
rails d model hogeするのが
面倒だな...と思ったので、migrationもrails consoleに任せられないかどうかを試してみました。

####事前準備

普通にrails consoleに入ってmodelとmigration classを作成します。

$ rails c --sandbox
class Person < ApplicationRecord; end

class CreatePeople < ActiveRecord::Migration[6.0]
  def change
    create_table :people do |t|
      t.string :name
      t.integer :age

      t.timestamps
    end
  end
end

####migration

ActiveRecord::Migration.run(CreatePeople)
-- create_table(:people)
   (19.0ms)  SELECT sqlite_version(*)
   (1.0ms)  CREATE TABLE "people" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "age" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
   -> 0.0226s
=> [CreatePeople]

####rollback

ActiveRecord::Migration.revert(CreatePeople)
-- drop_table(:people)
   (0.5ms)  DROP TABLE "people"
   -> 0.0012s
=> nil

勿論、データ操作も可能です。

Person.create!(name: "John", age: 25)
   (0.2ms)  SAVEPOINT active_record_1
  Person Create (0.3ms)  INSERT INTO "people" ("name", "age", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "John"], ["age", 25], ["created_at", "2018-11-22 14:38:36.161985"], ["updated_at", "2018-11-22 14:38:36.161985"]]
   (0.1ms)  RELEASE SAVEPOINT active_record_1
=> #<Person id: 1, name: "John", age: 25, created_at: "2018-11-22 14:38:36", updated_at: "2018-11-22 14:38:36">
Person.first
  Person Load (0.4ms)  SELECT  "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Person id: 1, name: "John", age: 25, created_at: "2018-11-22 14:38:36", updated_at: "2018-11-22 14:38:36">

・ActiveRecord::Migration.run
・ActiveRecord::Migration.revert
共に、可変長引数のメソッドのため、複数classの指定が可能です。
https://api.rubyonrails.org/classes/ActiveRecord/Migration.html

####もっと楽をしたい人の為に...
上記メソッドを呼ばずとも、migrationは可能です。

class Person < ApplicationRecord; end

class CreatePeople < ActiveRecord::Migration[6.0]
  create_table :people do |t|
    t.string :name
    t.integer :name

    t.timestamps
  end
end
-- create_table(:people)
   (1.5ms)  SELECT sqlite_version(*)
   (10.4ms)  CREATE TABLE "people" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
   -> 0.0197s
=> []

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?