1
1

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

【rails】seeds 作成時の "NoMethodError: undefined method `テーブル名1' for #<テーブル名2:0x000055f5fcc6c580> エラーの解決

Posted at

エラー原因

結論からいうと、has_many :テーブル名を書いていないからエラーが起こりました。

エラー状況

下記のような状態で、rails db:seedを実行したところ、
NoMethodError: undefined method 'products' for #<User:0x000055f5fcc6c580>が発生。

user = User.create!(
  last_name: "山田",
  first_name: "太郎",
  email: "user1@example.com",
  password: "password",
)

product = user.products.create!(
  product_name: "りんご",
  description: "新鮮なりんごです",
  user_id: user1.id,
)

実行結果 : エラー発生
`NoMethodError: undefined method 'products' for #<User:0x000055f5fcc6c580>`

解決

models/user.rb に下記のように書くことで解決。

has_many :products, dependent: :destroy

テーブル同士の関連付けが出来ていなかった為、エラーしていました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?