はじめに
次はもっと複雑です。
中間テーブルを用いたDB設計をしていきます。
紙に書いた後にQiitaに書き起こす。
効率よくならんものか、この頭…💦
…と、言ってないでさっさとやりましょう。
usersテーブル
| Column | Type | Options |
|---|---|---|
| string | null: false | |
| password | string | null: false |
| username | string | null: false |
※email/password/username空欄を許可しない「NOT NULL」を設定。【null: false】
Association
- has_many :posts
- has_many :comments
※usersテーブル⇆postsテーブル = 「1対多」
※usersテーブル⇆commentsテーブル = 「1対多」
なので両方とも【has_many】
postsテーブル
| Column | Type | Options |
|---|---|---|
| title | text | null: false |
| text | text | null: false |
| user_id | integer | null: false, foreign_key: true |
※/title/text/user_idは空欄を許可しない「NOT NULL」を設定。【null: false】
※user_idを外部キーとして設定。【foreign_key: true】
Association
- belongs_to :user
- has_many :comments
- has_many :posts_tags
- has_many :tags, through: :posts_tags
※postsテーブル⇆usersテーブル = 「多対1」なので【belongs_to】
※postsテーブル⇆commentsテーブル = 「1対多」
※postsテーブル⇆posts_tagsテーブル = 「1対多」
→【has_many】
※postsテーブル⇆tagsテーブル = 「1対多」かつ、中間テーブルとしてposts_tagsテーブルを設けている。
→【has_many **,through:】
tagsテーブル
| Column | Type | Options |
|---|---|---|
| text | text | null: false |
Association
-
has_many :posts_tags
-
has_many :posts, through: :posts_tags
※tagsテーブル⇆posts_tagsテーブル = 「1対多」なので【has_many】
※tagsテーブル⇆postsテーブル = 「1対多」かつ、中間テーブルとしてposts_tagsテーブルを設けている。
→【has_many **, through:】
posts_tagsテーブル
| Column | Type | Options |
|---|---|---|
| post_id | integer | null: false, foreign_key: true |
| tags_id | integer | null: false, foreign_key: true |
Association
- belongs_to :post
- belongs_to :tag
commentsテーブル
| Column | Type | Options |
|---|---|---|
| text | text | null: false |
| user_id | integer | null: false, foreign_key: true |
| group_id | integer | null: false, foreign_key: true |
Association
- belongs_to :post
- belongs_to :user
まとめ
・エンティティとその属性を明確に
・エンティティ間のリレーションを明確に
・どのデータにどんな制約がつくか
・ER図にして表す
これらが大事だと思った。
以上