0
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 1 year has passed since last update.

記事にコメント機能①

Posted at

記事にコメント

リレーションについて勉強
現在のdbの状況としては、 ユーザーがいて、その下にいくつかの記事が並んでいる状況。

記事とコメントの関係はというと
現在ある記事の下にさらに追加していく。
記事と紐づいてコメントがある。
記事が一つに対して、コメントが複数ある関係を1対nと言います。

1対n
articlesテーブルには、id,user_id,titleが存在します。

新しくcommentsテーブルを作成。
中身は、id,article_id,titleとなります。
article_idが、何を表すかというと、articleテーブルにおいてのid部分を示しています。
これで、コメントがどの記事と紐づいているかがわかる。

Commentモデルを作成
ターミナルにて、モデルを作れば、モデルとマイグレーションファイルが作成される。
$rails g model Comment

g:ジェネレートの略(生み出す、引き起こす)

create    db/migrate/20230303113656_create_comments.rb
create    app/models/comment.rb

これで、マイグレーションファイル、モデルが作成されました。

db/migrate/20230303113656_create_comments.rb
を開く
アーティクルと紐づく形になるので、アーティクルidが必要

db/migrate/20230206145433_create_articles.rb
こちらを見ると、

t.references :user, null: false

と同じ感じにする。

db/migrate/20230303113656_create_comments.rb

t.references :article,null: false

を追加。
null: falseをつけるのは、コメントにはアーティクルidが必ず必要である 。

t.text :content, null: false

さらに追加。

これで、マイグレーションファイルは完成。

ターミナルにて

$rails db:migrate

を実行。create_table、migratedと記載があるので、マイグレーションファイルが実行されたことがわかります。

db/schema.rb
を確認すると

 create_table "comments", force: :cascade do |t|
    t.integer "article_id", null: false
    t.text "content", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["article_id"], name: "index_comments_on_article_id"
  end

コメンツテーブルがあることがわかります。

モデルも確認
app/models/comment.rb
以上のもがあることを確認できました。
id :integer not null, primary key
content :text not null
created_at :datetime not null
updated_at :datetime not null
article_id :integer not null

これで、dbの準備はできました。

app/models/article.rb

 has_many :comments

とする。
これは、アーティクルがコメントをいっぱいもっている 。という関係なので、has_many :commentsとしました。

app/models/comment.rb
こちらでは、記事に紐づいてるとするために

belongs_to :article

注意ポイント:app/models/article.rbでは、has_many :commentsと複数形になっている。
しかし、コメントからすれば一つの記事に紐づいているので、単数形になる。

app/models/article.rb

has_many :comments, dependent: destroy

を追加。
この記事が削除された時、コメントも一緒に削除するよという意味。

ここまでで、データベースとモデルの設定が完了。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?