跳过依赖于: :destroy 的验证

Pra*_* KJ 3 ruby activerecord ruby-on-rails

我有一个用户和一个公司模型,如下所示。公司模式已经得到了一些验证。

用户.rb

    after_create :create_tables!

    def create_tables!
      companies.create!(handle: "random_handle")
   end
Run Code Online (Sandbox Code Playgroud)

公司.rb

before_destroy :check_for_presence_of_a_company!

def check_for_presence_of_a_company!
  if user.companies.count <= 1
    errors.add(:base, 'You cannot delete all of your companies.')
    throw(:abort)
  end
end
Run Code Online (Sandbox Code Playgroud)

当用户第一次创建帐户时,我在用户模型中使用after_create为他创建一个公司,在删除公司之前,他应该至少有一个公司。

但问题是当用户尝试删除他的帐户时,上述公司验证会抛出错误。

当用户删除其帐户时,应忽略上述验证company.rb。我怎样才能做到这一点?谢谢。

编辑

user.rb中我更新了

has_many :companies,dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

has_many :companies,dependent: :delete_all
Run Code Online (Sandbox Code Playgroud)

但是company.rb

has_many :categories, dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

并显示违反外键约束错误。将其从 destroy 更新为 delete_all 也不起作用。

小智 6

我假设你有这个(尽管你没有展示它):

class User
  has_many :companies, dependent: :destroy
end
Run Code Online (Sandbox Code Playgroud)

如果是这样,您可以更改:destroy:delete_all

has_many :companies, dependent: :delete_all
Run Code Online (Sandbox Code Playgroud)

根据https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

:delete_all导致所有关联的对象直接从数据库中删除(因此不会执行回调)。

(注意,由于Company不会运行回调,因此如果您需要删除其他关联,则必须单独处理这些关联。)