1
0

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 5 years have passed since last update.

ツイートアプリのDB設計

Last updated at Posted at 2020-04-11

はじめに

大苦戦しています。DB設計。
こうして書き起こすことで、自分の頭にも叩き込んでいる状態😅
手を動かせばどうにかなるかなぁと思い、早速やっていきます。

tweetアプリの DB設計

usersテーブル

Column Type Options
email string null: false
password string null: false
nickname string null: false
※email/password/nicknameのそれぞれにNOT NULL制約を指定。【null: false】

Association

  • has_many :tweets
  • has_many :comments
※usersテーブルは、tweetsテーブル、commentsテーブルに対して「1対多」なので、has_manyで関連付け。

tweetsテーブル

Column Type Options
image text
text text
user_id integer null: false, foreign_key: true
※image/textは特にOptionが無いので空欄。
※user_idを外部キーとして設定。commentsテーブルからuser_idを参照できるようにする。

Association

  • belongs_to :user
  • has_many :comments
※tweetsテーブル⇆usersテーブル = 「多対1」なので【belongs_to】
※tweetsテーブル⇆commentsテーブル = 「1対多」なので【has_many】

commentsテーブル

Column Type Options
text text null: false
user_id integer null: false, foreign_key: true
tweet_id integer null: false, foreign_key: true
※textは空欄を許可しない「NOT NULL」を設定。【null: false】
※user_idは「NOT NULL」と外部キー設定。【foreign_key: true】
※tweet_idも同上。

Association

  • belongs_to :tweet
  • belongs_to :user
※commentsテーブル⇆tweetテーブル = 「多対1」なので【belongs_to】
※commentsテーブル⇆usersテーブル = 「多対1」なので【belongs_to】

と、こんな感じで仕上がる訳だ。
うんうん、なんとなく頭でつながった感。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?