Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::RecordInvalid Validation failed: Account must exist

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

models

user.rb

class User < ApplicationRecord
   belongs_to :account
end

account.rb

class Account < ApplicationRecord
    has_many :users
end

controllers

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
like image 437
bottles Avatar asked May 21 '26 19:05

bottles


1 Answers

With Rails 5, belongs_to association is required by default. So you should make the account optional.

belongs_to :account, optional: true
like image 60
demir Avatar answered May 24 '26 19:05

demir