0
0

More than 3 years have passed since last update.

モデルとテーブル作成

Last updated at Posted at 2020-11-17

モデルとテーブルの作成を備忘録として残す。

ターミナルでモデルを作成

rails g model モデル名

下記のログが出ればOK

      invoke  active_record
      create    db/migrate/000000000_create_tweets.rb
      create    app/models/モデル名.rb
      invoke    test_unit
      create      test/models/モデル名_test.rb
      create      test/fixtures/モデル名.yml

モデル名.rbが作成される。

テーブルの作成

モデルを生成すると一緒にマイグレーションファイルが作られる。
dbフォルダのmigrateファイルにある。これを編集する。

class Createモデル名(頭文字は大文字) < ActiveRecord::Migration[6.0]
  def change
    create_table :モデル名 do |t|
      t.string :name
      t.string :text
      t.text :image
      t.timestamps
    end
  end
end

t.あとが「型」、:に続くのが「カラム名」です。

型の種類

string : 文字列
text : 長い文字列
integer : 整数
float : 浮動小数
decimal : 精度の高い小数
datetime : 日時
timestamp : タイムスタンプ
time : 時間
date : 日付
binary : バイナリデータ
boolean : Boolean

マイグレーションの実行

rails db:migrate

以下のようなログが出ればOK

== 20xxxxxxxxxx CreateTweets: migrating =====================================
-- create_table(:tweets)
   -> 0.0148s
== 20xxxxxxxxxx CreateTweets: migrated (0.0149s) ============================

最後に、rails s でローカルサーバを再起動
rails c でデータが保存されていることを確認

[1] pry(main)> Tweet.create(name: "take", text: "apple")

以下のようにログが出てデータの保存ができているのを確認

  (4.4ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
   (0.3ms)  BEGIN
  Tweet Create (0.7ms)  INSERT INTO `tweets` (`name`, `text`, `created_at`, `updated_at`) VALUES ('take', 'apple', '2020-11-17 03:06:52.758040', '2020-11-17 03:06:52.758040')
   (3.2ms)  COMMIT
=> #<Tweet:0x00007ff6e6ca6770
 id: 1,
 name: "take",
 text: "apple",
 image: nil,
 created_at: Tue, 17 Nov 2020 03:06:52 UTC +00:00,
 updated_at: Tue, 17 Nov 2020 03:06:52 UTC +00:00>

確認できたら完了!!

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