gpt4 book ai didi

ruby-on-rails - ActiveRecord::RecordInvalid 验证失败:帐户必须存在

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:25 26 4
gpt4 key购买 nike

使用 ruby​​ 2.6 和 rails 5.2Rails 控制台中的用户创建引发

ActiveRecord::RecordInvalid (Validation failed: Account must exist)

我刚刚生成了Devise User,所以暂时没有user_controller

模型

用户.rb

class User < ApplicationRecord
belongs_to :account
end

账户.rb

class Account < ApplicationRecord
has_many :users
end

Controller

accounts_controller.rb

class AccountsController < ApplicationContoller
def new
redirect_to root_path
unless current_user.account.nil?
@account = Account.new
end
def create
@account = Account.new(account_params)
if @account.save
current_user.account = @account
current_user.save
redirect_to root_path, success: "Your account has been created!"
else
render :new
end
end
........
end

最佳答案

Rails 5 中,默认需要 belongs_to 关联。因此,您应该将帐户设置为可选。

belongs_to :account, optional: true

关于ruby-on-rails - ActiveRecord::RecordInvalid 验证失败:帐户必须存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57682556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com