【问题标题】:ActiveRecord::RecordInvalid Validation failed: Account must existActiveRecord::RecordInvalid 验证失败:帐户必须存在
【发布时间】:2019-08-27 21:36:54
【问题描述】:

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

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

我刚刚生成了设计用户,所以暂时没有user_controller

型号

user.rb

class User < ApplicationRecord
   belongs_to :account
end

account.rb

class Account < ApplicationRecord
    has_many :users
end

控制器

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    对于 Rails 5,默认情况下需要 belongs_to 关联。因此,您应该将帐户设为可选。

    belongs_to :account, optional: true
    

    【讨论】:

      【解决方案2】:

      感谢@demir 的回答,我已经处理这个问题3 天了。 现在,我想分享一下我调试这个问题的方法。 第1步: 在控制台中创建一个用户来理解问题:

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

      => #

      注意:我将新用户保存在变量@u 上,因为我想在保存后使用用户

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

      importat:查看错误消息。 在我的用例中,我得到:

      `用户存在 (1.6ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "corner@gmail.com"], ["LIMIT", 1]] (0.4ms) 回滚 回溯(最近一次通话最后): 1:来自(irb):8 ActiveRecord::RecordInvalid(验证失败:级别必须存在)

      ` 第三步:获取错误信息进行调试:

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

      查看错误 和@u.errors.details => {:level=>[{:error=>:blank}]}

      总结: 尝试在控制台上创建新用户,使用保存!方法,当你遇到错误时, 试试@VARIABLE_USE__TO_CREATE_USER.errors.details。 再次感谢@demir

      【讨论】:

        猜你喜欢
        • 2020-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多