Using ruby 2.6 & rails 5.2 User creation in rails console raises
ActiveRecord::RecordInvalid (Validation failed: Account must exist)
I just generated Devise User, so there is no user_controller for now
class User < ApplicationRecord
belongs_to :account
end
class Account < ApplicationRecord
has_many :users
end
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
With Rails 5, belongs_to association is required by default. So you should make the account optional.
belongs_to :account, optional: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With