はじめに
大苦戦しています。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】
と、こんな感じで仕上がる訳だ。
うんうん、なんとなく頭でつながった感。