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.

ユーザーと記事を紐付け⑤

Last updated at Posted at 2023-03-02

seedファイルを修正

データベースのスキーマが変更したので、seedを修正していきます。

db/seeds.rb
現在

10.times do
  Article.create(
    title: Faker::Lorem.sentence(word_count: 5),
    content: Faker::Lorem.sentence(word_count: 100)
  )
end

ダミーのデータを作るものがある。

しかし、これは、ユーザーidがないので、表示されない😭

User.create!(email: 'yumako@example.com', password: 'password')

!をつけておけば、保存されなかったときにエラーが起こる👍

こんな感じでユーザーを作成。

User.create!(email: 'rikutyan@example.com', password: 'password')

も一つ適当に作成

yumako = User.create!(email: 'yumako@example.com', password: 'password')
rikutyan = User.create!(email: 'rikutyan@example.com', password: 'password')

それぞれ、こうしておきます。

つくったら、インスタンスが返ってくるので、ユーザーインスタンスを取得できる。

5.times do
  yumako.articles.create!(
    title: Faker::Lorem.sentence(word_count: 5),
    content: Faker::Lorem.sentence(word_count: 100)
  )
end

こんな感じで作成。

5.times do
  rikutyan.articles.create!(
    title: Faker::Lorem.sentence(word_count: 5),
    content: Faker::Lorem.sentence(word_count: 100)
  )
end

もう一つも同じように👍

これは、今までと同じで、user.article.create
とするとユーザーと紐づいた記事が作成できる。

ターミナルにて

$rails db:seed

とやれば作成される。

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?