LoginSignup
0
0

More than 3 years have passed since last update.

RailsでEnum宣言を使ってモデルを作成する

Last updated at Posted at 2021-04-16

enumとは?

日本語訳は、「列挙型」
列挙:一つ一つ数え立てて挙げること。並べ立てること。

カラムに対して、数値ごとに対応する任意の名前をつけることができる。

enum宣言を採用するメリット

□ dbの可読性向上、管理しやすい
□ 日本語化にも応用が効く

追加したいDB

項目名 フィールド名 null 備考
メッセージID id string false
送信元ユーザーID send_by string false
送信先ユーザー send_to string false
メッセージ本文 discription text false
作成日時 create_date datetime false
APIに送信できたかの確認 api_status string false enum宣言で拡張性を持たせる

手順

STEP01. docker上でレターモデルを追加

作るときは普通にstringで作る。
integerでもいいけど、stringの方がdefault値を設定するときに数字でなく文字列で記載ができるのでより可読性が高い。
お好みでどうぞ。

idカラムは自動生成されるので、オプションでつける必要はありません。

% docker-compose run --rm web rails g model Letter send_by:string send_to:string description:text api_status:string --no-fixture

以下の様なDBファイルができる。

db/migrate/yyyyMMddhhmmss_create_letters.rb
class CreateRatings < ActiveRecord::Migration[5.2]
  def change
    create_table :letters do |t|
      t.string :send_by
      #...略

      t.string :api_status

      #...略
  end
end

以下の様にnot null制約と、default値を追記して保存します。

db/migrate/yyyyMMddhhmmss_create_letters.rb
class CreateRatings < ActiveRecord::Migration[5.2]
  def change
    create_table :letters do |t|
      t.string :id, null: false
      t.string :send_by, null: false
      t.string :send_to, null: false
      t.text :discription, null: false
      t.datetime :create_date, null: false
      t.string :api_status, defalut: 'success'

      t.timestamps
  end
end

STEP02. 対象モデルにenum宣言を記入

ここから対象モデルにenum宣言を書き込んでください。

app/models/letter.rb
class Letter < ApplicationRecord
  enum api_status: {
      sending: 'sending',
      success: 'success',
      failure: 'failure'
  }
end

STEP03. Rails db:migrateする

terminal.
% docker-compose exec web bundle exec rails db:migrate

参照させていただいたサイト様たち

Qiita. 【Rails】Enumってどんな子?使えるの?

Qiita. Rails - enumの使い方

Qiita. 【enum】 rails enumを利用してデータの可読性をあげよう

StuckOverFlow. How to store enum as string to database in rails

https://web-camp.io/magazine/archives/16862

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