rails c からユーザーをアクティブ化する際の ActiveRecord の新しいエラー

数ヶ月前までは、以下のような方法でユーザーを作成できました。

sudo -s
cd /var/discourse
./launcher enter app
rails c
u = User.create(username: "dunderhead", email: "dunderhead@live.com", password: "password")
u.activate

現在、activate ステップで以下のエラーが発生します。

[7] pry(main)> u.activate
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
from /var/www/discourse/vendor/bundle/ruby/3.2.0/gems/activerecord-7.0.8/lib/active_record
/associations/collection_association.rb:342:in `_create_record'

どうすればよいでしょうか?

ユーザーを作成すると、ユーザーIDは取得されますか?取得されないと疑っていますが、その理由はわかりません。

「いいね!」 1

いいえ。

[4] pry(main)> u = User.create(username: "dunderhead", email: "dunderhead@live.com", password: "password")
=> #<User:0x00007fb0c48b17e0
 id: nil,
 username: "dunderhead",
 created_at: nil,
 updated_at: nil,
 name: nil,
 seen_notification_id: 0,
 last_posted_at: nil,
 password_hash: nil,
 salt: nil,
 active: false,
 username_lower: nil,
 last_seen_at: nil,
 admin: false,
 last_emailed_at: nil,
 trust_level: 0,
 approved: false,
 approved_by_id: nil,
 approved_at: nil,
 previous_visit_at: nil,
 suspended_at: nil,
 suspended_till: nil,
 date_of_birth: nil,
 views: 0,
 flag_level: 0,
 ip_address: nil,
 moderator: false,
 title: nil,
 uploaded_avatar_id: nil,
 locale: nil,
 primary_group_id: nil,
 registration_ip_address: nil,
 staged: false,
 first_seen_at: nil,
 silenced_till: nil,
 group_locked_trust_level: nil,
 manual_locked_trust_level: nil,
 secure_identifier: nil,
 last_digest_at: nil,
 flair_group_id: nil,
 last_seen_reviewable_id: nil,
 password_algorithm: nil>

エラーメッセージで示唆されているように、アクティブ化する前にユーザーを保存しようとしましたが、うまくいきませんでした。「parent」が何を意味するのかわかりません。

[5] pry(main)> u.save
=> false
[6] pry(main)> u.activate
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
from /var/www/discourse/vendor/bundle/ruby/3.2.0/gems/activerecord-7.0.8/lib/active_record/
associations/collection_association.rb:342:in `_create_record'

ここで検証に失敗しているためです。

例:パスワードが短すぎます。

次のように例外を伝播させることができます。

u.save!

これにより、たとえば次のようになります。

ActiveRecord::RecordInvalid: Validation failed: Password is too short (minimum is 10 characters)
from /home/robert/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activerecord-7.0.8.1/lib/active_record/validations.rb:80:in `raise_validation_error'

より迅速にこれを行うには、create の後に感嘆符を追加します。

 u = User.create!(username: "dunderhead", email: "dunderhead@live.com", password: "password")

ID は、create 時または修正後に save するまで割り当てられません。

インスタンス化されたオブジェクトがあって初めて、その上でメソッドを実行できます。

「いいね!」 4

ありがとうございます。パスワードが短すぎたようです。すべて正常に動作しています。

「いいね!」 1

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.