Ruby on rails Rails 5 dependent::destroy不';行不通

Ruby on rails Rails 5 dependent::destroy不';行不通,ruby-on-rails,rails-activerecord,ruby-on-rails-5,Ruby On Rails,Rails Activerecord,Ruby On Rails 5,我有以下课程: class Product < ApplicationRecord belongs_to :product_category def destroy puts "Product Destroy!" end end class ProductCategory < ApplicationRecord has_many :products, dependent: :destroy def destroy puts "Categor

我有以下课程:

class Product < ApplicationRecord
  belongs_to :product_category

  def destroy
    puts "Product Destroy!"
  end

end

class ProductCategory < ApplicationRecord
  has_many :products, dependent: :destroy

  def destroy
    puts "Category Destroy!"
  end
end
在Rails控制台中运行以下语句时:
ProductCategory.destroy\u all

Category Destroy!
Category Destroy!
Category Destroy!
注:我有三个类别,每个类别有一个以上的产品。我可以通过
ProductCategory.find(1).products
确认它,它返回一个products数组。我听说Rails 5中的实现发生了更改。关于如何让它工作,有什么意见吗

编辑


我最终想要的是,一次性软删除一个类别和所有相关产品。这可能吗?还是必须在销毁前回调中迭代每个产品对象?(我的最后一个选项)

您应该使用销毁方法调用super:

def destroy
  super 
  puts "Category destroy"
end

但我绝对不会建议您跳过活动模型方法。

所以我最后就是这样做的:

class Product < ApplicationRecord
  belongs_to :product_category

  def destroy
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end

end

class ProductCategory < ApplicationRecord
  has_many :products, dependent: :destroy

  def destroy
    # run all callback around the destory method
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end
end
类产品

我从destroy返回true确实会使update\u属性有点危险,但我也在ApplicationController级别捕获异常,因此对我们来说效果很好。

删除两种destroy方法,然后重试。在我看来,您过度使用了active\u model destroy方法,应该调用“super”在destroy?我真的不建议覆盖ActiveRecord方法。让你自己像
update\u as\u destromed
update\u as\u destromed\u all
一样,而不是覆盖现有的。听起来你想要“软删除”。是的,我已经编辑了我的问题。从他的问题来看,它不会起作用,因为记录仍然会被销毁。他不想这样是的,这就是他想做的,但我的答案是指他的问题,那就是为什么依赖::销毁不起作用。他不是在问如何实现他想做的更新。
class Product < ApplicationRecord
  belongs_to :product_category

  def destroy
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end

end

class ProductCategory < ApplicationRecord
  has_many :products, dependent: :destroy

  def destroy
    # run all callback around the destory method
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end
end