使用 ruby 2.6 和rails 5.2 Rails 控制台中的用户创建引发
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/