2
votes

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
2

2 Answers

2
votes

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

belongs_to :account, optional: true
0
votes

Thank you @demir for that answer, I had been dealing with this problem for 3 days. Now, I would like to share the way I did to debug this problem. Step 1: create a user in the console to undertand the problem:

@u=User.new("id"=>"2030","username"=>"kam corner","email"=> "[email protected]","contact"=> "78542036","status"=> "1","password"=> "corneroftiassale","password_confirmation"=> "corneroftiassale")

=> #

Note: i save the new user on variable @u, because i want to user after to save

2:irb(main):004:0> @u.save!

importat: see the errors message. on my use case,i get:

`User Exists (1.6ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "[email protected]"], ["LIMIT", 1]] (0.4ms) ROLLBACK Traceback (most recent call last): 1: from (irb):8 ActiveRecord::RecordInvalid (Validation failed: Level must exist)

` step 3: get the error message to debug:

irb(main):009:0> @u.save.errors

for see the errors and @u.errors.details => {:level=>[{:error=>:blank}]}

summary: try to create the new user on console, use the SAVE! method, when you get errors, try the @VARIABLE_USE__TO_CREATE_USER.errors.details. againt thank you @demir