わからないこと
Ruby on Railsを使用しています。UserとProfileという2つのモデルを関連付け、Profileモデルのデータをcreateメソッドを使って作成しようと試みましたが、エラーが吐かれました。原因がわからず困っています。出力されているエラーを読んで見ると、NoMethodError (undefined method `create!' for nil:NilClass)とありますので、createメソッドがないということなんでしょうが、createメソッドを上記の方法で使用すること自体が誤っていますか?
詳細
以下に記載した「モデルの関連付け」に記載したUserクラスでデータを作成し、userという変数に格納しています。Profileモデルを使用したデータがないため、createメソッドを使用して、新規にデータを作成しようとしました。
rb(main):002:0> user = User.first User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] => #<User id: 1, email: "test1@gmail.com", created_at: "2020-02-18 13:17:26", updated_at: "2020-02-18 13:17:26">
irb(main):004:0> user.profile Profile Load (0.1ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT ? [["user_id", 1], ["LIMIT", 1]] => nil
エラー内容
irb(main):008:0> user.profile.create!(name:'test') Traceback (most recent call last): 2: from (irb):8 1: from (irb):8:in `rescue in irb_binding' NoMethodError (undefined method `create!' for nil:NilClass)
モデルの関連付け
Ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 has_one :profile, dependent: :destroy 8end
Ruby
1class Profile < ApplicationRecord 2 belongs_to :user 3 4 validates :name, presence: true 5end 6
使用言語
- rails: 6.0.2.1
- Ruby: 2.6.3
- devise: 4.7.1
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/26 14:18
2020/02/27 08:04
2020/02/28 02:04