Skip to content

Instantly share code, notes, and snippets.

@mochiz
Last active October 14, 2024 02:46
Show Gist options
  • Save mochiz/a90490ed795f777316ad67d0a07399b4 to your computer and use it in GitHub Desktop.
Save mochiz/a90490ed795f777316ad67d0a07399b4 to your computer and use it in GitHub Desktop.
ツイッターのデータベース設計演習課題

フィーチャー

  • ユーザー一覧を表示できる
  • ユーザーとしてツイートできる
  • ユーザーとして他ユーザーのツイートに返信できる
  • ユーザーとして他ユーザーのツイートをリツイート、引用ツイートできる
  • ユーザーとして他ユーザーをフォローできる
  • ユーザーとして自分がフォローしているユーザー一覧を表示できる
  • ユーザーとして自分をフォローしているユーザー一覧を表示できる
  • ユーザーとしてリストを作成できる
  • ユーザーとしてリストに任意のユーザーを追加できる
  • ユーザーとしてリスト一覧を表示できる

モデル

  • user: ユーザー
    • has_many: tweets
    • has_many: follows
    • has_many: followees, throught: :follows, source: :followee
    • has_many: followers, throught: :follows, source: :follower
  • tweet: ツイート
    • belongs_to: user
    • body: text
    • category: string # ツイート種別。enum tweet, reply, retweet, quote default: tweet
    • belongs_to: parent_id, option: true # リプライ、リツイート、引用ツイートの対象ツイート ID
  • follow: フォロー関係
    • belongs_to: followee, class_name: 'User', foreign_key: 'follwee_id' # フォロー対象のユーザー
    • belongs_to: follower, class_name: 'User', foreign_key: 'follwer_id' # フォローしてるユーザー
  • list: リスト
    • belongs_to: user
    • name: string
  • list_member: リストメンバー
    • belongs_to: list
    • belongs_to: user

ER 図

erDiagram
%% ユーザー
users {
  id bigint
  name string
}

%% ツイート
tweets {
  id bigint
  body text
  category string
  parent_id bigint
}

%% フォロー関係
follows {
  id bigint
  followee_id bigint FK
  follower_id bigint FK
}

%% リスト
lists {
  id bigint
  user_id bigint
  name string
}

%% リストメンバー
list_members {
  id bigint
  user_id bigint
}

%% テーブル同士の関連を表現できます
users ||--o{ tweets : "has many"
users ||--o{ follows : "has many"
tweets |o--o{ tweets : "has_one"
users ||--o{ lists : "has many"
lists ||--o{ list_members : "has many"

Loading

データ

user: ユーザー

Aさん(ID: 1)
Bさん(ID: 2)
Cさん(ID: 3)
Dさん(ID: 4)
id name
1 A
2 B
3 C
4 D

follows: フォロー関係

1. AさんがBさんをフォロー
2. BさんがCさんをフォロー
id followee_id follower_id
1 2 1
2 3 2

lists: リスト、list_members: リストメンバー

1. AさんがリストAを作成
2. AさんがリストAにBさんを追加
3. BさんがリストBを作成
4. BさんがリストBにCさんを追加
5. BさんがリストBにDさんを追加

lists: リスト

id user_id name
1 1 A
2 2 B

list_members: リストメンバー

id liset_id user_id
1 1 2
2 2 3
3 2 4
ツイート関係の操作
1. Aさんが「hello」とツイート
2. Bさんが1に対して「hi」とリプライ
3. Cさんが2をリツイート
4. Aさんが2を引用ツイートして「how are you?」とツイート

tweets: ツイート

id user_id body category parent_id
1 1 "hello" "tweet" nil
2 2 "hi" "reply" 1
3 3 "" "retweet" 2
4 1 "how are you?" "qweet" 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment